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


当前回答

input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}

其他回答

我从这里得到了最好的答案,并创建了一个在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">

我也面临着同样的问题。这个终于对我有用了

jQuery.fn.putCursorAtEnd =  = function() {

  return this.each(function() {

    // Cache references
    var $el = $(this),
        el = this;

    // Only focus if input isn't already
    if (!$el.is(":focus")) {
     $el.focus();
    }

    // If this function exists... (IE 9+)
    if (el.setSelectionRange) {

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
      var len = $el.val().length * 2;

      // Timeout seems to be required for Blink
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);

    } else {

      // As a fallback, replace the contents with itself
      // Doesn't work in Chrome, but Chrome supports setSelectionRange
      $el.val($el.val());

    }

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

  });

};

我们可以这样称呼它:

var searchInput = $("#searchInputOrTextarea");

searchInput
  .putCursorAtEnd() // should be chainable
  .on("focus", function() { // could be on any event
    searchInput.putCursorAtEnd()
  });

它适用于safari, IE, Chrome, Mozilla。在移动设备上,我没有尝试过这种方法。

在这之后,我发现最好的方法是使用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);

在jQuery中,这是

$(document).ready(function () {
  $('input').focus(function () {
    $(this).attr('value',$(this).attr('value'));
  }
}

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