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

时间:2016-05-28 09:45:13

标签: javascript jquery range selection wysihtml5

我正在尝试使用超链接替换内容可编辑div中的某些关键字,因为用户正在键入。通过首先将整个字符串拆分为“”,然后抓取最近的单词,如果它是我的一个关键字,我在整个字符串中找到起始索引和结束索引,然后执行:

appgc=new AppGameContainer(new Game(gamename));

我插入的节点是我创建的超链接,但为了简洁起见,并没有在这里输入所有内容。

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

这是我对内容可编辑html的第一次破解,所以我不知道如何抓住最后一个节点,我也不确定使用我的单词的开头和结尾索引无论如何都会在那里工作,因为那些是基于整个div内容的长度。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

经过一段时间的睡眠后,我自己解决了这个问题:如果能够帮助别人的话可能会发表评论。

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