2016-05-28 166 views
0

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

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

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

我的问题是,在插入节点之后,我不能再在我的setStart()方法中使用myDiv.firstChild,因为我在用户输入的地方有新的节点。

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

任何帮助将不胜感激。

回答

1

经过一段时间的睡眠之后,我自己整理了一下:在重要的情况下可以帮助别人。

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