我试图强调身体内的所有匹配单词,但不是任何html标签内的单词.例如,给定的关键字是'para'.这是段落:
<p class="para"> Example of paragraph. Lorem ipsum dolor sit amet. </p>
Run Code Online (Sandbox Code Playgroud)
导致:
<p class="para">
Example of <strong>para</strong>graph. Lorem ipsum dolor sit amet.
</p>
Run Code Online (Sandbox Code Playgroud)
我知道这可以用JavaScript来实现,replace()但我对regex不太了解.
Phr*_*ogz 13
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);
}
}
}
?
Run Code Online (Sandbox Code Playgroud)
您也可以考虑调用类似......
function removeHighlights(root){
[].forEach.call(root.querySelectorAll('span.highlighted'),function(el){
el.parentNode.replaceChild(el.firstChild,el);
});
}
Run Code Online (Sandbox Code Playgroud)
...在你找到新的亮点之前(从DOM中删除旧的亮点).
为什么从头开始构建自己的突出显示功能可能是一个坏主意的原因是因为你肯定会遇到其他人已经解决的问题.挑战:
innerHTML)听起来很复杂?如果你想要一些功能,比如忽略突出显示,变音符号映射,同义词映射,iframe内搜索,分离词搜索等一些元素,这就变得越来越复杂.
使用现有的,实现良好的插件时,您不必担心上面提到的东西.Sitepoint上的第10篇jQuery文本荧光笔插件比较了流行的荧光笔插件.
mark.js是一个用纯JavaScript编写的插件,但也可以作为jQuery插件使用.它的开发目的是提供比其他插件更多的机会,可以选择:
或者你可以看到这个小提琴.
用法示例:
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
Run Code Online (Sandbox Code Playgroud)
它是免费的,并在GitHub上开发了开源(项目参考).
| 归档时间: |
|
| 查看次数: |
9469 次 |
| 最近记录: |