当您在 Stackoverflow 中单击此处的“提问”时,您会看到一条文本“您的编程问题是什么?请描述一下。”
我想要同样的东西,我需要做的就是将光标移动到文本字段的开头。我如何用 jquery 做到这一点?
当您在 Stackoverflow 中单击此处的“提问”时,您会看到一条文本“您的编程问题是什么?请描述一下。”
我想要同样的东西,我需要做的就是将光标移动到文本字段的开头。我如何用 jquery 做到这一点?
这可能有点矫枉过正,但这些功能有助于选择输入字段的一部分。
下面的代码将光标置于第二个字段的第一个字符上。
<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>
您可以使用 focus() 方法。如果我记得 jQuery,它是这样的: $("#question_input_field_id").focus(); (如果我问对了你的问题)
更新:在开头设置光标:
$("#question_input_field_id").focus();
$("#question_input_field_id").get(0).setSelectionRange(0,0);
如果您查看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>
真正发生的事情是,CSS 代码<span class="edit-field-overlay">
移动到输入框的顶部并在需要时显示隐藏……然后按照 Sejanus 的建议进行操作。
$('#txtYourTextBox').blur(function () {
var val = $("#txtYourTextBox").val();
$("#txtYourTextBox").val('');
setTimeout(function () { $("#txtYourTextBox").val(val); }, 20);
});