将光标移动到textarea / input的末尾,格式为

时间:2018-03-24 23:16:19

标签: jquery html

我使用这个jQuery代码将光标保存在textarea的末尾



jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    var $el = $(this),
      el = this;
    if (!$el.is(":focus")) {
      $el.focus();
    }
    if (el.setSelectionRange) {
      var len = $el.val().length * 2;
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);
    } else {
      $el.val($el.val());
    }
    this.scrollTop = 999999;
  });
};
(function() {
  var searchInput = $(".search");
  searchInput
    .putCursorAtEnd()
    .on("focus", function() {
      searchInput.putCursorAtEnd()
    });
})();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="mail.php" method="POST">
  <p>Name<input class="search" type="text" name="name" placeholder="Name">
    <p>Email</p> <input class="search" type="text" name="email" placeholder="Email">
    <p>Message for the author</p><textarea class="search" name="message" rows="6" cols="25" placeholder="Message"></textarea><br />
    <input type="submit" value="Send">
</form>
&#13;
&#13;
&#13;

它仍然没有对光标位置做任何事情。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

只有在完成焦点操作后才需要设置scrollTop属性,因此需要超时。

我建议使用此技巧在最后设置插入位置:清除输入并立即再次恢复。它使代码变得更小并且使您无需更改焦点(当焦点操作已经执行时,可能会将焦点转移到另一个输入元素):

"SELECT user_email FROM users INNER JOIN users_to_groups ON users.user_id = users_to_groups.user_id WHERE users_to_groups.group_id = ? AND users_to_groups.user_id = ?";
jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    var value = $(this).val();
    $(this).val("").val(value);
    setTimeout(function () {
        this.scrollTop = 999999;
    }.bind(this)); 
  });
};
(function() {
  var searchInput = $(".search");
  searchInput
    .putCursorAtEnd()
    .on("focus", function() {
      searchInput.putCursorAtEnd()
    });
})();

答案 1 :(得分:0)

&#13;
&#13;
(function() {
  var searchInput = $(".search")
    .on("focus", function(e) {
      var $target = $(e.currentTarget);
      var len = $target.val().length;
      setTimeout(function() {
        $target[0].setSelectionRange(len,len);
      }, 1);
    });
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="mail.php" method="POST">
  <p>Name<input class="search" type="text" name="name" placeholder="Name">
    <p>Email</p> <input class="search" type="text" name="email" placeholder="Email">
    <p>Message for the author</p><textarea class="search" name="message" rows="6" cols="25" placeholder="Message"></textarea><br />
    <input type="submit" value="Send">
</form>
&#13;
&#13;
&#13;

你可以这样做:

(function() {
  var searchInput = $(".search")
    .on("focus", function(e) {
      var $target = $(e.currentTarget);
      var len = $target.val().length;
      setTimeout(function() {
        $target[0].setSelectionRange(len,len);
      }, 1);
    });
})();