在 contenteditable div 中用 html 替换某些最后输入的单词

Replace certain last words typed with html in contenteditable div

我正在尝试在用户输入时用 hyper-link 替换内容可编辑 div 中的某些关键字。我通过首先用“”拆分整个字符串,然后抓取最近的单词,如果它是我的关键字之一,我可以在整个字符串中找到开始索引和结束索引,然后执行以下操作:

range.setStart(myDiv.firstChild, startOfWordIndex);
range.setEnd(myDiv.firstChild, endOfWordIndex);
range.deleteContents();
range.insertNode(...);

我要插入的节点是我创建的超级节点link,但为了简洁起见没有在此处全部输入。

我的问题是,插入该节点后,我无法再在我的 setStart() 方法中使用 myDiv.firstChild,因为我在用户输入的位置前面有新的节点。

这是我对内容可编辑的第一次尝试 html 所以我不确定如何获取最后一个节点,我也不确定使用我的单词的开始和结束索引无论如何都能在那里工作,因为这些是基于 div 内容的整个长度。

如有任何帮助,我们将不胜感激。

睡了一觉后,我自己解决了这个问题:大量评论以防万一可以帮助别人。

function replaceLastWordWithLink(editContent) {
    var selection, selectedRange, range, node, frag, el, selectionText, wordStart, wordEnd, currentWord;
    // set the selection
    selection = window.getSelection();
    // set the range by the cursor
    selectedRange = selection.getRangeAt(0);
    // set the "global" range
    range = document.createRange();
    // get all node contents of global range
    range.selectNodeContents(editContent);
    // get the node the cursor is in
    node = selectedRange.startContainer;
    // point the global range to node the cusor is in and start of 0
    range.setStart(node, 0);
    // point the global range to node the cursor is in and end of where cursor is
    range.setEnd(node, selectedRange.startOffset);
    // create the fragment for the contents
    frag = range.cloneContents();
    // create a pseudo element to place the fragment in
    el = document.createElement("span");
    // place fragment in pseudo element
    el.appendChild(frag);
    // get the text from the pseduo element
    selectionText = el.innerText;
    // pattern to see if there are spaces
    spacePattern = /\s/;
    if (!spacePattern.test(selectionText)) {
        // no spaces so the start of the word index is at 0
        wordStart = 0;
        // no spaces so end of the word index is just where the cusor is (the total length of the text)
        wordEnd = selectionText.length;
    } else {
        // split off the last word in the text
        currentWord = selectionText.split(/\s/).reverse()[0].toLowerCase();
        // get the start of the word's index in the string
        wordStart = selectionText.lastIndexOf(currentWord);
        // get the end of the word's index by adding start of word index to the word length
        wordEnd = wordStart + currentWord.length;
    }
    // now set the range to the current word
    range.setStart(node, wordStart);
    range.setEnd(node, wordEnd);
    // now remove the current word
    range.deleteContents();
    // now replace the word with the link
    var el = document.createElement("a");
    el.href = "http://www.yahoo.com";
    el.text = selectedText;
    range.insertNode(el);
}