HTML 中的全文搜索忽略标签/&
我最近看到了很多用于在 HTML 页面中搜索和突出显示术语的库.但是,我看到的每个库都有同样的问题,他们找不到部分包含在 html 标记中的文本和/或他们无法找到 & 表示的特殊字符.
I've recently seen a lot of libraries for searching and highlighting terms within an HTML page. However, every library I saw has the same problem, they can't find text partly encased in an html tag and/or they'd fail at finding special characters which are &-expressed.
示例:
<span> This is a test. This is a <b>test</b> too</span>
搜索测试";会找到第一个实例,但不会找到第二个.
Searching for "a test" would find the first instance but not the second.
示例b:
<span> Pencils in spanish are called lápices</span>
搜索lápices"或lapices"将无法产生结果.
Searching for "lápices" or "lapices" would fail to produce a result.
有没有办法绕过这些障碍?
Is there a way to circumvent these obstacles?
提前致谢!
推荐答案
你可以使用window.find()
在非 IE 浏览器和 TextRange
的 findText()
方法.这是一个例子:
You can use window.find()
in non-IE browsers and TextRange
's findText()
method in IE. Here's an example:
http://jsfiddle.net/xeSQb/6/
不幸的是,在版本 15 中切换到 Blink 渲染引擎之前的 Opera 不支持 window.find
或 TextRange
.如果您对此感到担忧,一个相当重量级的替代方案是使用 TextRange 和我的 Rangy 库,如下例所示:http://rangy.googlecode.com/svn/trunk/demos/textrange.html
Unfortunately Opera prior to the switch to the Blink rendering engine in version 15 doesn't support either window.find
or TextRange
. If this is a concern for you, a rather heavyweight alternative is to use a combination of the TextRange and CSS class applier modules of my Rangy library, as in the following demo: http://rangy.googlecode.com/svn/trunk/demos/textrange.html
以下代码是对上述小提琴的改进,每次执行新搜索时不突出显示以前的搜索结果:
The following code is an improvement of the fiddle above by unhighlighting the previous search results each time a new search is performed:
function doSearch(text,color="yellow") {
if (color!="transparent") {
doSearch(document.getElementById('hid_search').value,"transparent");
document.getElementById('hid_search').value = text;
}
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, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<input type="text" id="search">
<input type="hidden" id="hid_search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">
<div id="content">
<p>Here is some searchable text with some lápices in it, and more lápices, and some <b>for<i>mat</i>t</b>ing</p>
</div>
相关文章