Window.find()应该可以完成这项工作。
虽然目前还没有标准化,但几乎所有主流的较新版本的浏览器都支持它,例如 Google Chrome、Firefox、IE、Safari、Opera,以及 iPhone/Android/Amazon Fire 平板电脑和手机上的浏览器等。
下面是一个示例实现:
/*
* Search for text in the window ignoring tags
*
* Parameters:
* text: a string to search for
* backgroundColor:
* "yellow" for example, when you would like to highlight the words
* "transparent", when you would like to clear the highlights
* */
function doSearch(text, backgroundColor) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, backgroundColor);
sel.collapseToEnd();
}
document.designMode = "off";
}
}
代码来自 Tim Down使用 Window.find() 的实现
在搜索之前,HTML 文本如下所示:
<p>Here is some searchable text with some lápices in it, and some
<b>for<i>mat</i>t</b>ing bits, and a URL
<a href="https://www.google.com">Google Search Engine</a> as a link.
</p>
搜索文本后,例如 ,some lápices in it, and some formatting bits, and a URL Google
HTML 文本将更改为:
<p>Here is some searchable text with <span style="background-color: yellow;">some lápices in it, and some
<b>for<i>mat</i>t</b>ing bits, and a URL
</span><a href="https://www.google.com"><span style="background-color: yellow;">Google </span>Search Engine</a> as a link.
</p>
请参阅jsfiddle 上的代码。