Javascript选择文本突出显示概率 [英] Javascript selected text highlighting prob
问题描述
我有一个带有文字内容的html页面。在选择任何文本并按突出显示按钮时,我可以更改所选文本的样式以突出显示相同的文本。为了实现这个功能,我编写了以下方法。
I have a html page with text content. On selecting any text and pressing the highlight button, I can change the style of the selected text to highlight the same. To implement this feature, i have written the following method.
sel = window.getSelection();
var range = sel.getRangeAt(0);
var span = document.createElement('span');
span.className = "highlight" + color;
range.surroundContents(span);
如果选择没有html标签的文本,但是当文本有任何html时,这个工作正常标签介于两者之间,它给出了错误
This is working fine if you choose a text with no html tag, but when the text has any html tag in between, it is giving error
无法在'Range'上执行'surroundContents':Range已部分选择了非文本节点。
Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.
如何解决这个问题。是否可以为每个部分分别突出显示相同的内容(除以html标签)?
How to solve this problem. Is it possible to highlight the same separately for each part(divided by html tags)?
推荐答案
if (window.getSelection) {
var sel = window.getSelection();
if (!sel) {
return;
}
var range = sel.getRangeAt(0);
var start = range.startContainer;
var end = range.endContainer;
var commonAncestor = range.commonAncestorContainer;
var nodes = [];
var node;
for (node = start.parentNode; node; node = node.parentNode){
var tempStr=node.nodeValue;
if(node.nodeValue!=null && tempStr.replace(/^\s+|\s+$/gm,'')!='')
nodes.push(node);
if (node == commonAncestor)
break;
}
nodes.reverse();
for (node = start; node; node = getNextNode(node)){
var tempStr=node.nodeValue;
if(node.nodeValue!=null && tempStr.replace(/^\s+|\s+$/gm,'')!='')
nodes.push(node);
if (node == end)
break;
}
for(var i=0 ; i<nodes.length ; i++){
var sp1 = document.createElement("span");
sp1.setAttribute("class", "highlight"+color );
var sp1_content = document.createTextNode(nodes[i].nodeValue);
sp1.appendChild(sp1_content);
var parentNode = nodes[i].parentNode;
parentNode.replaceChild(sp1, nodes[i]);
}
}
这篇关于Javascript选择文本突出显示概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!