0

我需要设置输入的光标位置。我可以让它在 Chrome 中正常工作,但我在使用 IE 时遇到了问题。我发现在 IE9/10 中运行良好的代码,但我找不到任何在 IE8 和更早版本中运行的代码。

这就是我为 Chrome 所拥有的:

var cursorPosition = 5;
var textArea = $('.the-input-I-Need');
textArea[0].selectionStart = cursorPosition;
textArea[0].selectionEnd = cursorPosition;
//now the cursor would be at the 5th spot in the input

任何人都知道为 IE 执行此操作的方法吗?我可以使用 jQuery,但没有其他插件。

4

1 回答 1

2

There's a question regarding getting and setting of the caret position in IE on this question: Get caret position in textarea (IE)

It also references an answer for actually getting the caret position here: How to get the start and end points of selection in text area?

There's a healthy amount of code that's specific to dealing with IE, but it will accomplish what you're trying to do. Note that the getter function returns a selection range, just as the setter can be used to set a selection range. In this case, you'd just call it with startOffset equaling endOffset:

setSelection(el, startOffset, endOffset);

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionStart);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}
于 2013-08-15T21:10:03.990 回答