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


当前回答

我喜欢接受的答案很多,但它停止工作在Chrome。在Chrome浏览器中,光标要走到最后,需要改变输入值。解决方法如下:

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

其他回答

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

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。在移动设备上,我没有尝试过这种方法。

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

我刚在iOS中发现,设置textarea。textContent属性每次都会将光标放在textarea元素中文本的末尾。这种行为是我的应用程序中的一个bug,但似乎是你可以故意使用的东西。

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

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

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