如何使用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);

当前回答

我必须让它为可满足的元素和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最好成绩;

其他回答

在IE中移动光标到某个位置这段代码就足够了:

var range = elt.createTextRange();
range.move('character', pos);
range.select();

我知道这是一个非常老的帖子,但我认为我应该提供一个更简单的解决方案,只使用jQuery更新它。

function getTextCursorPosition(ele) {   
    return ele.prop("selectionStart");
}

function setTextCursorPosition(ele,pos) {
    ele.prop("selectionStart", pos + 1);
    ele.prop("selectionEnd", pos + 1);
}

function insertNewLine(text,cursorPos) {
    var firstSlice = text.slice(0,cursorPos);
    var secondSlice = text.slice(cursorPos);

    var new_text = [firstSlice,"\n",secondSlice].join('');

    return new_text;
}

使用ctrl-enter添加新行(就像在Facebook中):

$('textarea').on('keypress',function(e){
    if (e.keyCode == 13 && !e.ctrlKey) {
        e.preventDefault();
        //do something special here with just pressing Enter
    }else if (e.ctrlKey){
        //If the ctrl key was pressed with the Enter key,
        //then enter a new line break into the text
        var cursorPos = getTextCursorPosition($(this));                

        $(this).val(insertNewLine($(this).val(), cursorPos));
        setTextCursorPosition($(this), cursorPos);
    }
});

我乐于接受批评。谢谢你!

更新:这个解决方案不允许正常的复制和粘贴功能的工作(即ctrl-c, ctrl-v),所以我将不得不编辑这在未来,以确保该部分再次工作。如果你知道怎么做,请在这里评论,我很乐意测试。谢谢。

我有两个功能:

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

然后你可以像这样使用setCaretToPos:

setCaretToPos(document.getElementById("YOURINPUT"), 4);

活生生的例子与文本区域和输入,显示使用jQuery:

function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function setCaretToPos(input, pos) { setSelectionRange(input, pos, pos); } $("#set-textarea").click(function() { setCaretToPos($("#the-textarea")[0], 10) }); $("#set-input").click(function() { setCaretToPos($("#the-input")[0], 10); }); <textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea> <br><input type="button" id="set-textarea" value="Set in textarea"> <br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit"> <br><input type="button" id="set-input" value="Set in input"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

截至2016年,我在Chrome, Firefox, IE11,甚至IE8上进行了测试和工作。堆栈片段不支持IE8)。

这里的解决方案是正确的,除了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;
};

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