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


当前回答

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

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

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

其他回答

试试下面的代码:

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

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

我得出的解决方案如下:

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

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

我从这里得到了最好的答案,并创建了一个在Chrome中工作良好的功能。

您需要将逻辑封装在一个超时中,因为您必须等待焦点完成后才能访问所选内容 要将光标放在末尾,选择起始点需要放在末尾 为了滚动到输入字段的末尾,scrollLeft需要匹配scrollWidth

/** * Upon focus, set the cursor to the end of the text input * @param {HTMLInputElement} inputEl - An HTML <input> element */ const setFocusEnd = (inputEl) => { setTimeout(() => { const { scrollWidth, value: { length } } = inputEl; inputEl.setSelectionRange(length, length); inputEl.scrollLeft = scrollWidth; }, 0); }; document .querySelector('input') .addEventListener('focus', (e) => setFocusEnd(e.target)); html, body { width: 100%; height: 100%; margin: 0; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; } input:focus { background-color: hsla(240, 100%, 95%, 1.0); } <input type="text" placeholder="Search..." value="This is some really, really long text">

While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

跨浏览器和所有输入类型的解决方案相当简单:

获取输入值并将其存储在变量中 关注输入 将输入值设置为存储值

这样,光标就位于输入元素的末尾。 所以你所要做的就是这样(使用jquery,提供一个人希望关注的元素选择器是通过点击元素的“data-focus-element”数据属性和函数在点击后执行)。foo的元素):

$('.foo').click(function() {
    element_selector = $(this).attr('data-focus-element');
    $focus = $(element_selector);
    value = $focus.val();
    $focus.focus();
    $focus.val(value);
});

Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.

在这之后,我发现最好的方法是使用setSelectionRange函数,如果浏览器支持它;如果不是,则恢复使用Mike Berrow回答中的方法(即将值替换为本身)。

我还将scrollTop设置为一个高值,以防我们在一个垂直滚动的文本区域。(在Firefox和Chrome中,使用任意的高值似乎比$(this).height()更可靠。)

我已经把它作为一个jQuery插件。(如果你没有使用jQuery,我相信你仍然可以很容易地得到主旨。)

我在IE6, IE7, IE8, Firefox 3.5.5,谷歌Chrome 3.0, Safari 4.0.4, Opera 10.00中进行了测试。

它可以在jquery网站上作为PutCursorAtEnd插件使用。为方便起见,1.0版的代码如下:

// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange)
        {
        // ... then use it
        // (Doesn't work in IE)

        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);