2016-05-28 125 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); 
}