2016-05-28 4 views
0

ユーザーが入力している間に、コンテンツ編集可能なdivの特定のキーワードをハイパーリンクで置き換えようとしています。私は最初に ""で全体の文字列を分割し、次に最も新しい単語をつかんで、それが私のキーワードの1つであれば、文字列全体の開始インデックスと終了インデックスを見つけ出し、contenteditable divにhtmlと入力した特定の最後の単語を置き換えます。

私が挿入したノードは、私が作成したハイパーリンクですが、簡潔にするためにすべてここに入力しませんでした。

私の問題は、ノードが挿入された後、ユーザーが入力している場所の前に新しいノードがあるため、myDiv.firstChildをmyStiv()メソッドで使用できなくなることです。

これはコンテンツ編集可能な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); 
} 
関連する問題