什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?


当前回答

适用于所有浏览器和所有情况:

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>

我在IE中遇到了同样的问题(在通过RJS/prototype设置焦点后)。 当该字段已经有一个值时,Firefox已经在末尾留下了光标。IE将光标强制移到文本的开头。

我得出的解决方案如下:

<input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="this.value = this.value;" name="search"/>

这在IE7和FF3中都有效,但在现代浏览器中不起作用(见评论),因为没有指定UA必须覆盖这种情况下的值(根据元策略编辑)。

document.querySelector(“输入”)。addEventListener('focus', e => { Const {value} = e.target; e.target.setSelectionRange(价值。长度,value.length); }); <input value="my text" />

拿出一些答案。制作单行jquery。

$('#search').focus().val($('#search').val());

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通常表示(到)最后一个字符。这也是这种情况,但我在文档中找不到明确提到的这种行为。