如何在文本框中将光标移动到下一个/上一个单词?

3

如何使用Javascript在textarea中将光标移动到下一个或上一个单词?我正在尝试在HTML textarea中复制Emacs命令“向前一个单词”和“向后一个单词”。

我可以使用rangyinputs获取当前的插入符/光标位置,但我还不确定如何有效地移动到下一个单词,而不使用可能在非常长的文本上变慢的各种分割。


你有尝试过什么吗? - Alex Tartan
这可能会有帮助:https://dev59.com/GXRB5IYBdhLWcg3w1Khe - Anders
2个回答

2

我使用了这里setCaretToTextEnd()以及这里.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);
  }
}

0

请查看此fiddle。我使用了jQuery在文本区域中设置光标位置的函数来更改光标位置。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接