什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过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;
}
其他回答
我想把光标放在一个“div”元素的末尾,其中contentteditable = true,我得到了一个解决方案与Xeoncross代码:
<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
<div id="test" contenteditable="true">
Here is some nice text
</div>
这个函数很神奇:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
适用于大多数浏览器,请检查,这段代码将文本和焦点放在div元素(不是输入元素)文本的末尾
https://jsfiddle.net/Xeoncross/4tUDk/
谢谢,Xeoncross
如果先设置值,再设置焦点,光标将始终出现在最后。
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
这是用来测试的小提琴 https://jsfiddle.net/5on50caf/1/
input = $('input');
input.focus().val(input.val()+'.');
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}
简单。在编辑或更改值时,首先放置焦点,然后设置值。
$("#catg_name").focus();
$("#catg_name").val(catg_name);
设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!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();
}