ajs*_*sie 31 javascript jquery
当您在Stackoverflow中单击"提问"时,您会看到一条文字"您的编程问题是什么?具有描述性."
我想要同样的事情,我需要的是将光标移动到文本字段的开头.我怎么用jquery做到这一点?
Mic*_*Mic 26
可能是一个过度杀伤,但这些功能有助于选择输入字段的一部分.
下面的代码将光标放在第二个字段的第一个字符处.
<html>
<head>
<title>so</title>
</head>
<body>
<input value="stack" />
<input value="overflow" />
<script>
var inp = document.getElementsByTagName('INPUT')[1];
if (inp.createTextRange) {
var part = inp.createTextRange();
part.move("character", 0);
part.select();
} else if (inp.setSelectionRange) {
inp.setSelectionRange(0, 0);
}
inp.focus();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Sej*_*nus 12
您可以使用focus()方法.如果我回想一下jQuery,就像这样:$("#question_input_field_id").focus(); (如果我的问题是正确的)
更新:在开头设置光标:
$("#question_input_field_id").focus();
$("#question_input_field_id").get(0).setSelectionRange(0,0);
Run Code Online (Sandbox Code Playgroud)
如果你查看stackoverflow的源代码>问问题,你会发现:
<table style="width:668px">
<tr>
<td style="width:50px"><label for="title">Title</label></td>
<td style="padding-left:5px"><input id="title" name="title" type="text" maxlength="300" tabindex="100" style="width:610px" value="">
<span class="edit-field-overlay">What's your programming question? Be descriptive.</span>
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
真正发生的是CSS代码<span class="edit-field-overlay">移动到输入框的顶部并在需要时显示隐藏......并且只是执行Sejanus的建议.