Set mouse focus and move cursor to end of input using jQuery

后端 未结 19 2070
醉话见心
醉话见心 2020-12-04 06:42

This question has been asked in a few different formats but I can\'t get any of the answers to work in my scenario.

I am using jQuery to implement command history wh

19条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 07:10

    Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

    It uses setSelectionRange if supported, else has a solid fallback.

    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;
      });
    };
    

    Then you can just do:

    input.putCursorAtEnd();
    

提交回复
热议问题