Javascript 替换contenteditable div中用html键入的某些最后的单词
我正在尝试在用户键入时用超链接替换内容可编辑div中的某些关键字。我能很好地处理他们键入的第一个单词,首先用“”拆分整个字符串,然后抓取最近的单词,如果它是我的关键字之一,我会在整个字符串中找到开始索引和结束索引,然后执行以下操作:Javascript 替换contenteditable div中用html键入的某些最后的单词,javascript,jquery,range,selection,wysihtml5,Javascript,Jquery,Range,Selection,Wysihtml5,我正在尝试在用户键入时用超链接替换内容可编辑div中的某些关键字。我能很好地处理他们键入的第一个单词,首先用“”拆分整个字符串,然后抓取最近的单词,如果它是我的关键字之一,我会在整个字符串中找到开始索引和结束索引,然后执行以下操作: range.setStart(myDiv.firstChild, startOfWordIndex); range.setEnd(myDiv.firstChild, endOfWordIndex); range.deleteContents(); range.ins
range.setStart(myDiv.firstChild, startOfWordIndex);
range.setEnd(myDiv.firstChild, endOfWordIndex);
range.deleteContents();
range.insertNode(...);
我插入的节点是我创建的超链接,但为了简洁起见,没有在这里全部键入
我的问题是,在插入该节点后,我不能再在setStart()方法中使用myDiv.firstChild,因为在用户键入的位置前面有新的节点
这是我第一次破解内容可编辑html,因此我不确定如何抓取最后一个节点,也不确定使用word的开始索引和结束索引是否可以在那里工作,因为它们基于div内容的整个长度
任何帮助都将不胜感激。经过一段时间的睡眠后,我自己解决了这个问题:发表了大量评论,以防in可以帮助其他人
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);
}