代码之家  ›  专栏  ›  技术社区  ›  Peanut

使用JavaScript将光标放在文本输入元素中文本的末尾

  •  270
  • Peanut  · 技术社区  · 16 年前

    在焦点设置到元素之后,通过JavaScript将光标放置在输入文本元素的文本末尾的最佳方式(我认为是最简单的方式)是什么?

    27 回复  |  直到 16 年前
        1
  •  213
  •   Community CDub    8 年前

    有一个简单的方法可以让它工作 浏览器。

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

    然而,由于一些浏览器的*怪癖,一个更具包容性的答案看起来更像这样

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

    使用jQuery (设置侦听器,但不需要其他设置)

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

    (借用 addEvent 作用于 this answer )

    // Basic cross browser addEvent
    function addEvent(elem, event, fn){
    if(elem.addEventListener){
      elem.addEventListener(event, fn, false);
    }else{
      elem.attachEvent("on" + event,
      function(){ return(fn.call(elem, window.event)); });
    }}
    var element = document.getElementById('el');
    
    addEvent(element,'focus',function(){
      var that = this;
      setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
    });
    <input id='el' type='text' value='put cursor at end'>

    怪癖

    Chrome有一个奇怪的特性,焦点事件在光标移动到字段之前触发;这把我的简单解决方案搞砸了。解决此问题的两个选项:

    1. 您可以将0毫秒的超时添加到 defer the operation until the stack is clear )
    2. 您可以从更改事件 focus mouseup

    另外,@vladkras指出,一些较旧版本的Opera在有空格的情况下计算长度时存在错误。为此,您可以使用一个大于字符串的巨大数字。

        2
  •  185
  •   Mike Berrow    16 年前

    Firefox已经将光标放在末尾,而字段已经有了值。IE正在强制将光标移到文本的开头。

    我得出的解决办法如下:

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

        3
  •  181
  •   sth    14 年前

    试试这个,它对我很有效:

    //input is the input element
    
    input.focus(); //sets focus to element
    var val = this.input.value; //store the value of the element
    this.input.value = ''; //clear the value of the element
    this.input.value = val; //set that value back.  
    

    要将光标移动到末尾,输入必须首先具有焦点,然后当值更改时,它将转到末尾。如果将.value设置为相同,则在chrome中不会更改。

        4
  •  100
  •   teedyay    15 年前

    setSelectionRange 功能(如果浏览器支持);如果没有,则恢复使用Mike Berrow答案中的方法(即,将值替换为自身)。

    我也在准备 scrollTop textarea . (使用任意的高值似乎比 $(this).height() 在Firefox和Chrome中。)

    我把它做成了一个jQuery插件。(如果您不使用jQuery,我相信您仍然可以很容易地获得要点。)

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

    它在jquery.com上作为 PutCursorAtEnd plugin . 为方便起见,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);
    
        5
  •  22
  •   Hallgeir Engen    13 年前
    <script type="text/javascript">  
        function SetEnd(txt) {  
          if (txt.createTextRange) {  
           //IE  
           var FieldRange = txt.createTextRange();  
           FieldRange.moveStart('character', txt.value.length);  
           FieldRange.collapse();  
           FieldRange.select();  
           }  
          else {  
           //Firefox and Opera  
           txt.focus();  
           var length = txt.value.length;  
           txt.setSelectionRange(length, length);  
          }  
        }   
    </script>  
    

    这个函数在IE9、Firefox 6.x和Opera 11.x中都适用

        6
  •  20
  •   Andy Raddatz    5 年前

    https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

    function moveCursorToEnd(id) {
      var el = document.getElementById(id) 
      el.focus()
      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();
      }
    }
    <input id="myinput" type="text" />
    <a href="#" onclick="moveCursorToEnd('myinput')">Move cursor to end</a>
        7
  •  17
  •   Hejner    7 年前

    我在chrome上尝试了以下方法,取得了很大的成功

    $("input.focus").focus(function () {
        var val = this.value,
            $this = $(this);
        $this.val("");
    
        setTimeout(function () {
            $this.val(val);
        }, 1);
    });
    

    快速概述:

    它接受每个类关注的输入字段,然后将输入字段的旧值存储在变量中,然后将空字符串应用于输入字段。

    然后等待1毫秒,再次输入旧值。

        8
  •  11
  •   Gary Yuseferi    9 年前

    易于理解的编辑或更改值时,请先放置焦点,然后设置值。

    $("#catg_name").focus();
    $("#catg_name").val(catg_name);
    
        9
  •  11
  •   seeker_of_bacon    5 年前

    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 通常指最后一个字符。这一次也是如此,但我在文档中找不到明确提到这种行为的地方。

        10
  •  7
  •   sth    14 年前

    否则光标的行为会很奇怪,我们需要它在末尾。

    <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>
    
        11
  •  5
  •   terma    10 年前

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

        12
  •  5
  •   Konrad G    7 年前

    我很喜欢这个被接受的答案,但是它在Chrome中停止工作了。在Chrome中,要将光标移到末尾,需要更改输入值。解决办法如下:

    <input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>
    
        13
  •  4
  •   Kishore Newton    5 年前

    试试这个可以与香草JavaScript一起使用。

    <input type="text" id="yourId" onfocus=" let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">
    

    在Js中

    document.getElementById("yourId").focus()
    
        14
  •  3
  •   sth    14 年前

    在jQuery中,这是

    $(document).ready(function () {
      $('input').focus(function () {
        $(this).attr('value',$(this).attr('value'));
      }
    }
    
        15
  •  3
  •   Gary Yuseferi    9 年前

    +++++++解决方案+++++++

    1. 您需要一个JS函数,如下所示:

      function moveCursorToEnd(obj) {
      
        if (!(obj.updating)) {
          obj.updating = true;
          var oldValue = obj.value;
          obj.value = '';
          setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
        }
      
      }
      
    2. 你需要在onfocus和onclick事件中给这个家伙打电话。

      <input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
      

    它适用于所有设备和浏览器!!!!

        16
  •  2
  •   Gary Yuseferi    11 年前

    我刚在iOS中发现,设置 textarea.textContent

        17
  •  2
  •   HanKrum    9 年前
    var valsrch = $('#search').val();
    $('#search').val('').focus().val(valsrch);
    
        18
  •  2
  •   Ravi Ram    8 年前

    拿着一些答案。。生成单行jquery。

    $('#search').focus().val($('#search').val());
    
        19
  •  1
  •   Decko    14 年前

    如果输入字段只需要一个静态默认值,我通常使用jQuery执行此操作:

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

    这似乎适用于所有浏览器。

        20
  •  1
  •   l.varga    8 年前

    虽然这可能是一个有很多答案的老问题,但我遇到了一个类似的问题,没有一个答案是我想要的和/或解释得很差。selectionStart和selectionEnd属性的问题是它们不存在于输入类型number中(虽然问题是针对文本类型的,但我认为这可能会帮助其他需要关注其他输入类型的人)。因此,如果您不知道函数将关注的输入类型是否为类型号,则无法使用该解决方案。

    • 集中输入
    • 将输入值设置为存储值

    这样,光标就位于输入元素的末尾。
    因此,您所要做的就是这样(使用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);
    });
    

    为什么这样做有效?简单地说,当调用.focus()时,焦点将添加到输入元素的开头(这是这里的核心问题),而忽略输入元素中已经有值这一事实。但是,当输入的值发生更改时,光标将自动放置在输入元素中值的末尾。因此,如果您使用之前在输入中输入的相同值覆盖该值,则该值看起来将保持不变,但光标将移动到末尾。

        21
  •  1
  •   hjrshng    4 年前

    document.querySelector('input').addEventListener('focus', e => {
      const { value } = e.target;
      e.target.setSelectionRange(value.length, value.length);
    });
    <input value="my text" />
        22
  •  1
  •   Wenfang Du Saurabh P Bhandari    3 年前
    const end = input.value.length
    
    input.setSelectionRange(end, end)
    // 👇 scroll to the bottom if a textarea has long text
    input.focus()
    
        23
  •  0
  •   linuts    13 年前

    此代码的变体是…也可以使用!对于Firefox、IE、Safari、Chrome。。

    在服务器端代码中:

    txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
    

    在Javascript中:

    function sendCursorToEnd(obj) {
        var value =  $(obj).val(); //store the value of the element
        var message = "";
        if (value != "") {
            message = value + "\n";
         };
        $(obj).focus().val(message);
        $(obj).unbind();
     }
    
        24
  •  0
  •   Usman Shaukat    7 年前

    如果先设置值,然后设置焦点,光标将始终显示在末尾。

    $("#search-button").click(function (event) {
        event.preventDefault();
        $('#textbox').val('this');
        $("#textbox").focus();
        return false;
    });
    

    https://jsfiddle.net/5on50caf/1/

        25
  •  0
  •   Lexsoul    6 年前

    我想把光标放在一个“div”元素的末尾,contenteditable=true,我得到了一个解决方案 Xeoncross code :

    <input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
    
    <div id="test" contenteditable="true">
        Here is some nice text
    </div>
    

     function pasteHtmlAtCaret(html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
    
                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);
    
                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    }
    

    适用于大多数浏览器,请检查它,此代码将文本和焦点放在div元素(非输入元素)的文本末尾

    https://jsfiddle.net/Xeoncross/4tUDk/

    谢谢,Xeoncross

        26
  •  0
  •   amku91    6 年前

    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(即Chrome、Mozilla)中使用它。在移动设备上,我没有尝试过这个。

        27
  •  0
  •   Roberto Godoy    6 年前

    检查此解决方案!

    //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>
        28
  •  0
  •   Elijah    5 年前

    超级简单(您可能需要关注输入元素)

    inputEl = getElementById('inputId');
    var temp = inputEl.value;
    inputEl.value = '';
    inputEl.value = temp;
    
        29
  •  -1
  •   sth    14 年前

    在文本区:

    onfocus() = sendCursorToEnd(this);
    

    function sendCursorToEnd(obj) { 
    var value = obj.value; //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
    };
    $(obj).focus().val(message);}
    
        30
  •  -1
  •   Rory O'Kane Erce    13 年前

    这里有一个 jsFiddle demo convert it to plain JavaScript 如果你需要的话。

    在JavaScript中,最重要的部分是:

    var endIndex = textField.value.length;
    if (textField.setSelectionRange) {
       textField.setSelectionRange(endIndex, endIndex);
    }
    

    以下是来自JSFIDLE的代码,因此即使JSFIDLE消失,也会保留此答案:

    moveCursorToEnd = (textField) ->
      endIndex = textField.value.length
      if textField.setSelectionRange
        textField.setSelectionRange(endIndex, endIndex)
    
    jQuery ->
      $('.that-field').on 'click', ->
        moveCursorToEnd(this)
    
    <div class="field">
        <label for="pressure">Blood pressure</label>:
        <input class="that-field" type="text" name="pressure" id="pressure" value="24">
    </div>
    <p>
        Try clicking in the text field. The cursor will always jump to the end.
    </p>
    
    body {
        margin: 1em;
    }
    
    .field {
        margin-bottom: 1em;
    }