如何使用java脚本突出显示一个特定字符串的所有发生? [英] how to highlight all the occurrence of a particular string in a div with java script?
问题描述
我需要通过选择一个字符串
来突出显示特定div中所有字符串的出现次数,一旦我选择一个单词并单击一个按钮,它需要突出显示div内所有的出现,
例如 - 如果我选择
板球是比赛
blockquote>
它应该突出所有出现的板球比赛有些可能是这样的板球是比赛或板球 是游戏
解决方案您可以使用
TextRange
在IE中,window.find()
在其他浏览器中。
这个答案显示了如何去做。它将匹配跨越元素边界的文本,并使用
document.execCommand()
为您进行高亮显示。或者,也可以使用 $ b,James Padolsey最近发布了一个我没有用过的脚本,但看起来可以提供帮助: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/
i need to highlight all the occurrences of a string in particular div by selecting a string, once i select a word and click a button it need to highlight all its occurrence inside a div,
eg - if i select
cricket is game
it should highlight all the occurrences of cricket is game some may be like this cricket is game or cricket is game
解决方案You can get the browser to do the hard work for you using a
TextRange
in IE andwindow.find()
in other browsers.This answer shows how to do it. It will match text that crosses element boundaries and does the highlighting for you using
document.execCommand()
.Alternatively, James Padolsey recently published a script that I haven't used but looks like it could help: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/
这篇关于如何使用java脚本突出显示一个特定字符串的所有发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!