【问题标题】:How to move cursor to next/previous word in textarea?如何将光标移动到textarea中的下一个/上一个单词?
【发布时间】:2015-08-15 19:25:25
【问题描述】:
如何使用 Javascript 将光标移动到文本区域中的下一个或上一个单词?我正在尝试在 HTML 文本区域中复制 Emacs 命令“前进一个单词”和“后退一个单词”。
我可以使用 rangyinputs 获取当前插入符号/光标位置,但我还不确定如何有效地移动到下一个单词而不使用各种拆分,这些拆分在很长的文本上可能会很慢。
【问题讨论】:
标签:
javascript
jquery
html
dom
textarea
【解决方案1】:
我使用了来自here 的setCaretToTextEnd() 和来自here 的.selectRange()。以下函数使用 Emacs 样式的插入符号位置,并且比遍历单词更有效。
function nextWord(input) {
let currentCaretPosition = input.selectionStart;
// -1 Because Emacs goes to end of next word.
let nextWordPosition = input.value.indexOf(' ', currentCaretPosition) - 1;
if (nextWordPosition < 0) {
input.setCaretToTextEnd();
} else {
input.selectRange(nextWordPosition);
}
}
function previousWord(input) {
let currentCaretPosition = input.selectionStart;
// +1 Because Emacs goes to start of previous word.
let previousWordPosition = input.value.lastIndexOf(' ', currentCaretPosition) + 1;
if (previousWordPosition < 0) {
input.selectRange(0);
} else {
input.selectRange(previousWordPosition);
}
}
【解决方案2】:
看到这个fiddle。我使用了jQuery Set Cursor Position in Text Area 中的函数来改变光标的位置。
function nextWord(input) {
var words = input.value.split(" "),
index = 0;
for (var i in words) {
var word = words[i];
if (index+word.length >= input.selectionStart) {
setCaretToPos(input, index+word.length+1);
break;
}
index += word.length+1;
}
}
function previousWord(input) {
var words = input.value.split(" ").reverse(),
index = input.value.length;
for (var i in words) {
var word = words[i];
if (index+1 <= input.selectionStart) {
setCaretToPos(input, index-word.length);
break;
}
index -= word.length+1;
}
}