如何使用jQuery设置文本字段中的光标位置?我有一个文本字段的内容,我希望用户的光标定位在一个特定的偏移时,他们聚焦在该字段。代码应该是这样的:

$('#input').focus(function() {
  $(this).setCursorPosition(4);
});

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

当前回答

只要记住在函数调用后返回false,如果你使用方向键,因为Chrome fricks frack否则。

{
    document.getElementById('moveto3').setSelectionRange(3,3);
    return false;
}

其他回答

我正在使用这个:http://plugins.jquery.com/project/jCaret

这适用于我的Safari 5在Mac OSX, jQuery 1.4:

$("Selector")[elementIx].selectionStart = desiredStartPos; 
$("Selector")[elementIx].selectionEnd = desiredEndPos;

设置焦点之前,你已经插入文本到文本区,从而?

$("#comments").focus();
$("#comments").val(comments);

这里的解决方案是正确的,除了jQuery扩展代码。

扩展函数应该遍历每个选定的元素并返回此值以支持链接。以下是正确的版本:

$.fn.setCursorPosition = function(pos) {
  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;
};

我必须让它为可满足的元素和jQuery工作,并认为有人可能想要它准备好使用:

$.fn.getCaret = function(n) {
    var d = $(this)[0];
    var s, r;
    r = document.createRange();
    r.selectNodeContents(d);
    s = window.getSelection();
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return s.anchorOffset;
};

$.fn.setCaret = function(n) {
    var d = $(this)[0];
    d.focus();
    var r = document.createRange();
    var s = window.getSelection();
    r.setStart(d.childNodes[0], n);
    r.collapse(true);
    s.removeAllRanges();
    s.addRange(r);
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return this;
};

使用$(selector). getcaret()返回数字偏移量,$(selector). setcaret (num)建立偏移量并将焦点设置在元素上。

还有一个小提示,如果你从控制台运行$(selector). setcaret (num),它将返回console.log,但你不会看到焦点,因为它是在控制台窗口建立的。

D最好成绩;