JavaScript setSelectionRange() 方法和光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10180075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:11:35  来源:igfitidea点击:

JavaScript setSelectionRange() method and cursor position

javascript

提问by AndyW

I have the following piece of JavaScript for dynamically inserting unicode characters - represented below by the txtToIns variable - into a body of text

我有以下一段 JavaScript 用于动态插入 unicode 字符 - 在下面由 txtToIns 变量表示 - 到文本正文中

elmt.value = elmt.value.substring(0, elmt.selectionStart) + txtToIns + " " + elmt.value.substring(elmt.selectionStart, elmt.selectionEnd) + elmt.value.substring(elmt.selectionEnd, elmt.value.length) + " ";
elmt.focus();
elmt.value = elmt.value.trim();

With the above the cursor is always at the end of the text. Is there any way I can place it directly after txtToIns? And no, txtToIns.focus() won't work

上面的光标总是在文本的末尾。有什么办法可以将它直接放在 txtToIns 之后?不,txtToIns.focus() 不起作用

回答by Tim Down

I'm not sure what you're trying to do with the space characters in the textarea value, particularly the final one which will get trimmed off again two lines later, so I've ignored the spaces in my code below. I'm also not sure what you're trying to do with the text that was previously selected (if any), so I'm going to assume you want to overwrite it with the new text.

我不确定您要对 textarea 值中的空格字符做什么,特别是最后一个将在两行后再次修剪掉,所以我忽略了下面代码中的空格。我也不确定您要对之前选择的文本(如果有的话)做什么,所以我假设您想用新文本覆盖它。

Bear in mind that this will not work in IE < 9, which does not support selectionStart, selectionStartor setSelectionRange().

请记住,这在不支持selectionStart,selectionStart或 的IE < 9 中不起作用setSelectionRange()

Demo: http://jsfiddle.net/timdown/wPfVn/

演示:http: //jsfiddle.net/timdown/wPfVn/

Code:

代码:

var val = elmt.value;
var start = elmt.selectionStart, end = elmt.selectionEnd;
elmt.value = val.slice(0, start) + txtToIns + val.slice(end);
elmt.focus();
var caretPos = start + txtToIns.length;
elmt.setSelectionRange(caretPos, caretPos);

回答by Robert Messerle

When you change the value, the cursor will move to the end. You will have to manually reset the cursor position after you change its value.

当您更改值时,光标将移动到末尾。更改其值后,您必须手动重置光标位置。

Try this:

尝试这个:

var start = elmt.selectionStart,
    len   = txtToIns.length,
    pos   = start + len;
elmt.value = elmt.value.substring(0, start) + txtToIns + " " + elmt.value.substring(start) + " ";
elmt.focus();
elmt.value = elmt.value.trim();
elmt.setSelectionRange( pos, pos, 0 );

I also cleaned up some unnecessary logic in the line where you set the value. Hopefully I didn't break anything, but if I did, just revert to your original line. ?

我还在设置值的行中清理了一些不必要的逻辑。希望我没有破坏任何东西,但如果我破坏了,请恢复到您原来的路线。?