【问题标题】:Replace word before cursor, when multiple lines in contenteditable当 contenteditable 中有多行时,替换光标前的单词
【发布时间】:2018-06-12 12:41:57
【问题描述】:

我想替换 contenteditable div 中光标前的单词(另见 Detect the last written word when typing TAB in a textarea or contenteditable div)。

以下代码:

  1. 完全适用于contenteditable div 的第一段

  2. 不适用于contenteditable div 的下一段:

    未捕获的 IndexSizeError:无法在“Range”上执行“setStart”:偏移量 71 大于节点的长度 (38)。

contenteditable div的第2行按TAB时,我应该如何修改以下代码使其工作?

document.addEventListener("keydown", function(e) {
    var elt = e.target;
    if (elt.isContentEditable)
    {        
        if (e.keyCode == 9) {
            e.preventDefault();
            elt.focus();
            range = document.getSelection().getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(elt, 0);
            var words = range.toString().trim().split(' ');
            var lastWord = words[words.length - 1];
            if (lastWord) {
                var wordStart = range.toString().lastIndexOf(lastWord);
                var wordEnd = wordStart + lastWord.length;
                range.setStart(elt.firstChild, wordStart);
                range.setEnd(elt.firstChild, wordEnd);
                range.deleteContents();
                document.execCommand('insertText', false, "hello\nnewline");
                elt.normalize();
            }
        }
    }
});
<div contenteditable>Hello, click here and press TAB to replace this WORD<br>Also click here and press TAB after this ONE</div>

注意:我已经测试了来自 Replace specific word in contenteditable 的答案,但是当 contenteditable div 中有多行时它不起作用。

【问题讨论】:

    标签: javascript html contenteditable


    【解决方案1】:

    这行得通:

    document.addEventListener("keydown", function(e) {
        var elt = e.target;
        if (elt.isContentEditable)
        {        
            if (e.keyCode == 9) {
                e.preventDefault();
                elt.focus();
                sel = document.getSelection();
                sel.modify("extend", "backward", "word");
                range = sel.getRangeAt(0);
                console.log(range.toString().trim());
                range.deleteContents();
                var el = document.createElement("div");
                el.innerHTML = '<b>test</b> and a <a href="hjkh">link</a>';
                var frag = document.createDocumentFragment(), node;
                while (node = el.firstChild) {
                    frag.appendChild(node);
                }
                range.insertNode(frag);
                range.collapse();
            }
        }
    });
    &lt;div contenteditable&gt;Hello, press TAB to replace this WORD&lt;br&gt;Also press TAB after this ONE&lt;/div&gt;

    这是full solutiontextarea 和可内容编辑的div

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多