我试图突出显示正文内的所有匹配单词,但不突出显示任何 html 标记内的单词。例如,给出的关键字是“para”。这是该段落:
<p class="para"> Example of paragraph. Lorem ipsum dolor sit amet. </p>
导致:
<p class="para">
Example of <strong>para</strong>graph. Lorem ipsum dolor sit amet.
</p>
我知道这可以通过 JavaScript 实现replace()
但我对正则表达式不太了解。
Demo: http://jsfiddle.net/crgTU/7/
highlightWord(document.body,'para');
function highlightWord(root,word){
textNodesUnder(root).forEach(highlightWords);
function textNodesUnder(root){
var n,a=[],w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null,false);
while(n=w.nextNode()) a.push(n);
return a;
}
function highlightWords(n){
for (var i; (i=n.nodeValue.indexOf(word,i)) > -1; n=after){
var after = n.splitText(i+word.length);
var highlighted = n.splitText(i);
var span = document.createElement('span');
span.className = 'highlighted';
span.appendChild(highlighted);
after.parentNode.insertBefore(span,after);
}
}
}
您也可以考虑调用类似...
function removeHighlights(root){
[].forEach.call(root.querySelectorAll('span.highlighted'),function(el){
el.parentNode.replaceChild(el.firstChild,el);
});
}
…在您寻找新的高亮显示之前(从 DOM 中删除旧的高亮显示)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)