Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在IE8及更早版本中使用JavaScript设置光标位置?_Javascript_Jquery_Internet Explorer - Fatal编程技术网

如何在IE8及更早版本中使用JavaScript设置光标位置?

如何在IE8及更早版本中使用JavaScript设置光标位置?,javascript,jquery,internet-explorer,Javascript,Jquery,Internet Explorer,我需要设置输入的光标位置。我可以让它在Chrome中正常工作,但我在IE中遇到了问题。我发现了在IE9/10中可以正常工作的代码,但我找不到任何在IE8或更早版本中可以正常工作的代码 这就是我对Chrome的看法: var cursorPosition = 5; var textArea = $('.the-input-I-Need'); textArea[0].selectionStart = cursorPosition; textArea[0].selectionEnd = cursorP

我需要设置输入的光标位置。我可以让它在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,但没有其他插件。

关于IE中插入符号位置的获取和设置,在这个问题上有一个问题:

它还引用了此处实际获取插入符号位置的答案:

有大量特定于处理IE的代码,但它将完成您试图完成的任务。注意,getter函数返回一个选择范围,就像setter可以用来设置选择范围一样。在这种情况下,只需使用
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();
  }
}

FWIW,您要查找的单词是“插入符号”,而不是“游标”。您将函数命名为“setSelectionRange”,但您使用“setSelection”调用它