如何使用 Javascript 将光标移动到文本区域中的下一个或上一个单词?我正在尝试在 HTML 文本区域中复制 Emacs 命令“前进一个词”和“后退一个词”。
我可以使用 rangyinputs 获取当前插入符/光标位置, 但我还不确定如何在不使用各种拆分的情况下有效地移动到下一个单词,这些拆分在很长的文本上可能会很慢。
最佳答案
我使用了来自 here 的 setCaretToTextEnd()
和 .selectRange()
来自 here .以下函数使用 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);
}
}
关于javascript - 如何将光标移动到文本区域中的下一个/上一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32028479/