相关疑难解决方法(0)

jQuery在文本区域中设置光标位置

如何使用jQuery在文本字段中设置光标位置?我有一个包含内容的文本字段,我希望用户光标在关注字段时定位在某个偏移处.代码应该看起来像这样:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});
Run Code Online (Sandbox Code Playgroud)

setCursorPosition函数的实现是什么样的?如果您有一个内容为abcdefg的文本字段,则此调用将导致光标定位如下:abcd**|**efg.

Java有一个类似的功能,setCaretPosition.javascript是否存在类似的方法?

更新:我修改了CMS的代码以使用jQuery,如下所示:

new function($) {
  $.fn.setCursorPosition = function(pos) {
    if (this.setSelectionRange) {
      this.setSelectionRange(pos, pos);
    } else if (this.createTextRange) {
      var range = this.createTextRange();
      range.collapse(true);
      if(pos < 0) {
        pos = $(this).val().length + pos;
      }
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);
Run Code Online (Sandbox Code Playgroud)

html javascript jquery textfield

434
推荐指数
10
解决办法
33万
查看次数

标签 统计

html ×1

javascript ×1

jquery ×1

textfield ×1