简体   繁体   English

JavaScript setSelectionRange()方法和游标位置

[英]JavaScript setSelectionRange() method and cursor position

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? 有什么办法可以在txtToIns之后直接放置它吗? And no, txtToIns.focus() won't work 不,txtToIns.focus()不起作用

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

Bear in mind that this will not work in IE < 9, which does not support selectionStart , selectionStart or setSelectionRange() . 请记住,这不适用于IE <9,它不支持selectionStartselectionStartsetSelectionRange()

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

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. 希望我没有破坏任何东西,但如果我这样做,只需恢复原来的路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM