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


当前回答

如果输入字段只需要一个静态默认值,我通常用jQuery这样做:

$('#input').focus().val('Default value');

这似乎在所有浏览器中都有效。

其他回答

试试下面的代码:

$('input').focus(function () {
    $(this).val($(this).val());
}).focus()

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

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事件处理程序移动光标,需要超时

有一种简单的方法可以让它在大多数浏览器中工作。

this.selectionStart = this.selectionEnd = this.value.length;

然而,由于一些浏览器的特性,一个更全面的答案是这样的

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

使用jQuery(设置监听器,否则不需要)

$ (' # el) .focus(函数(){ Var that = this; () {setTimeout(函数。selectionStart = that。selectionEnd = 10000;},0); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <input id='el' type='text' value='put cursor at end'>

使用Vanilla JS(从答案中借用addEvent函数)

//基本的跨浏览器addEvent 函数addEvent(elem,事件,fn){ 如果(elem.addEventListener) { 初步的。addEventListener(事件,fn, false); 其他}{ 初步的。attachEvent(“on”+事件, 函数(){返回(fn。调用(elem window.event));}); }} var element = document.getElementById('el'); addEvent(元素、“焦点”函数(){ Var that = this; () {setTimeout(函数。selectionStart = that。selectionEnd = 10000;},0); }); <input id='el' type='text' value='put cursor at end'>


怪癖

Chrome有一个奇怪的怪癖,焦点事件在光标移动到字段之前被触发;这打乱了我简单的解决方案。有两个选项可以解决这个问题:

您可以添加一个0毫秒的超时(将操作延迟到堆栈清空为止) 您可以将事件从焦点更改为鼠标悬停。这对用户来说是相当烦人的,除非你仍然保持焦点。这两种选择我都不太喜欢。

此外,@vladkras指出,一些旧版本的Opera在有空格时,会错误地计算长度。为此,你可以使用一个巨大的数字,应该大于你的字符串。

检查这个解决方案!

//fn setCurPosition $.fn.setCurPosition = function(pos) { this.focus(); this.each(function(index, elem) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }); return this; }; // USAGE - Set Cursor ends $('#str1').setCurPosition($('#str1').val().length); // USAGE - Set Cursor at 7 position // $('#str2').setCurPosition(7); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p>Set cursor at any position</p> <p><input type="text" id="str1" value="my string here" /></p> <p><input type="text" id="str2" value="my string here" /></p>

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