Why using a selfmade highlighting function is a bad idea
开始从零开始建立您自己的突出功能可能是个坏主意, 原因是因为您肯定会遇到其他人已经解决的问题。 挑战 :
- You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g.
innerHTML
)
- If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
- You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I m talking about cross-browser tests!
听上去复杂吗? 如果您想要一些特征 比如忽略一些元素 从突出显示, diacritics映射,同义词映射, 在 iframes 内部搜索, 分开的单词搜索等等。 这变得越来越复杂 。
Use an existing plugin
当使用一个已有的、实施良好的插件时, 您不必担心上面提到的插件。 文章 < stronga href=" https://www. sitepoint.com/ 10- jquery- text- highlighter- plugins/ " rel=“ nofollow” > 10jQuery 文本提示插件 a/ strong> 与流行的突顯插件相比, 在站点上的插件 < /a/ strong> 。
Have a look at mark.js
< a href=" "https://markjs.io/" rel="nofollow">mark.js 是一个以纯 JavaScript 写成的插件,但也可以作为 jQuery 插件。 开发该插件是为了提供比其他插件更多的机会, 可以选择 :
- search for keywords separately instead of the complete term
- map diacritics (For example if "justo" should also match "justò")
- ignore matches inside custom elements
- use custom highlighting element
- use custom highlighting class
- map custom synonyms
- search also inside iframes
- receive not found terms
https://markjs.io/configurator.html" rel=“nofollow” >DEMO
也可以见“https://jsfiddle.net/julmot/vpav6tL1/" rel=“no follow”>这个小提琴 。
<强度 > 用户示例 强度 > :
// Highlight "keyword" in the specified context
$(".context").mark("keyword");
// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);
它在GitHub上自由开发了开放源码(项目参考资料 )。