什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
el.setSelectionRange(-1, -1);
https://codesandbox.io/s/peaceful-bash-x2mti
这个方法更新HTMLInputElement。selectionStart selectionEnd, 和selectionDirection属性一次调用。
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
在其他js方法中,-1通常表示(到)最后一个字符。这也是这种情况,但我在文档中找不到明确提到的这种行为。
其他回答
仍然需要中间变量,(参见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>
现在是2019年,上面的方法对我来说都没用,但这个方法管用,摘自https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/
函数moveCursorToEnd(id) var el = document.getElementById(id) el.focus () If(类型的el。selectionStart == "number") { 埃尔。selectionStart = el。selectionEnd = el.value.length; } else if(类型的el。createTextRange != "undefined") { var range = el.createTextRange(); range.collapse(假); range.select (); } } <input id="myinput" type="text" /> <a href="#" onclick="moveCursorToEnd('myinput')>移动光标到结束</a> .
我在IE中遇到了同样的问题(在通过RJS/prototype设置焦点后)。 当该字段已经有一个值时,Firefox已经在末尾留下了光标。IE将光标强制移到文本的开头。
我得出的解决方案如下:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="this.value = this.value;" name="search"/>
这在IE7和FF3中都有效,但在现代浏览器中不起作用(见评论),因为没有指定UA必须覆盖这种情况下的值(根据元策略编辑)。
超级简单(你可能需要关注input元素)
inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
我喜欢接受的答案很多,但它停止工作在Chrome。在Chrome浏览器中,光标要走到最后,需要改变输入值。解决方法如下:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>