什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
下面是我的答案的jsFiddle演示。演示使用CoffeeScript,但如果需要,可以将其转换为纯JavaScript。
JavaScript中重要的部分是:
var endIndex = textField.value.length;
if (textField.setSelectionRange) {
textField.setSelectionRange(endIndex, endIndex);
}
我把这个答案贴出来是因为我已经为有同样问题的其他人写过了。这个答案不像上面的答案那样涵盖那么多的边缘情况,但它适合我,并且有一个jsFiddle演示可以玩。
下面是来自jsFiddle的代码,所以即使jsFiddle消失了,这个答案也会被保留:
moveCursorToEnd = (textField) ->
endIndex = textField.value.length
if textField.setSelectionRange
textField.setSelectionRange(endIndex, endIndex)
jQuery ->
$('.that-field').on 'click', ->
moveCursorToEnd(this)
<div class="field">
<label for="pressure">Blood pressure</label>:
<input class="that-field" type="text" name="pressure" id="pressure" value="24">
</div>
<p>
Try clicking in the text field. The cursor will always jump to the end.
</p>
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
其他回答
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!Firefox, IE, Safari, Chrome..
在服务器端代码中:
txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
在Javascript中:
function sendCursorToEnd(obj) {
var value = $(obj).val(); //store the value of the element
var message = "";
if (value != "") {
message = value + "\n";
};
$(obj).focus().val(message);
$(obj).unbind();
}
适用于所有浏览器和所有情况:
function moveCursorToEnd(el) {
window.setTimeout(function () {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}, 1);
}
如果您需要从onFocus事件处理程序移动光标,需要超时
仍然需要中间变量,(参见var val=) 否则光标的行为很奇怪,我们需要它在最后。
<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>
如果输入字段只需要一个静态默认值,我通常用jQuery这样做:
$('#input').focus().val('Default value');
这似乎在所有浏览器中都有效。