javascript - 检测并替换 contenteditable div 上光标之前的单词

标签 javascript html contenteditable

如何检测 contenteditable 中光标之前的单词div 并用其他东西替换它? 这个 works for a textarea 但不适用于此 contenteditable div:

document.getElementById('a').addEventListener('keydown', e => {
  if (e.which == 9) {
    e.preventDefault();
    let endingIndex = e.target.selectionStart;     // does not work for contenteditable
    let startingIndex = endingIndex && endingIndex - 1;
    let value = e.target.innerHTML;
    let regex = /[ ]/;

    while(startingIndex){
      if(regex.test(value[startingIndex])){
        ++startingIndex;
        break;
      }
      --startingIndex;
    }
    console.log('word before cursor: ' + value.substring(startingIndex, endingIndex));
  }
  
});
<div contenteditable id="a">Please click here and hit TAB, the word before cursor should be replaced by something else.</div>

最佳答案

这是因为 selectionStart 是仅 HTMLInputElement 的属性。对象的类型。 也许你想看看这个gist或使用Range直接接口(interface)。

关于javascript - 检测并替换 contenteditable div 上光标之前的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803127/

相关文章:

javascript - 如何在视频背景上添加静音/取消静音按钮 [On Divi - WordPress]

javascript - 使用排序逻辑合并和排序多个数组

javascript - 指示浏览器仅从一个目录中选择

javascript - JS/ react : How to truncate text with an icon instead of ellipsis?

css - Opera 在带有 contenteditable 和 twitter bootstrap 的文档中添加了奇怪的间距,为什么?

html - 如何在最大高度的 contenteditable div 中显示滚动条?

javascript - Materialize CSS - 选择似乎无法呈现

asp.net-mvc - 为什么特殊字符撇号和其他字符在 HTMl 文件中显示为这样“,”

javascript - 单击模式“同意”按钮时未选中复选框

newline - contentEditable areas::force paragraphs for new lines - 跨浏览器