我想构建一个包含 HTML Web 控件的应用程序,并能够在 html 区域中搜索和突出显示多个短语,就像今天在 Web 浏览器中实现的那样。 主要思想是让搜索忽略 html 特殊标签,只引用真实文本(内部 html)。 我知道解决方案将包括编辑 DOM,但我不确定如何实现。 我在网上搜索了很多,我也看了Zavael的帖子,但不幸的是我找不到任何合适的答案。任何答案、示例或指导将不胜感激。
最佳答案
如果您指的是页面内 HTML 内容的内联搜索:首先我会说这可能不是一个好主意。您不应该取代浏览器的 native 功能。让用户按照他们习惯的方式做事。在不同的网站上保持一致的体验。
但是,如果您出于某些小众目的需要它,我认为这不会那么难。
jQuery 可以实现它。只是一个非常粗糙的开始:
//As you type in the search box...
$("#search_box").change(function() {
//...you search the searchable area (maybe use some regex here)
$("#search_area").html();
});
编辑:发问者问我是否可以详细说明代码。
//As you type in the search box...
$("#search_box").change(function() {
//This part of the code is called when the contents of the search box changes
//This is the contents of the searchable area:
$("#search_area").html();
//This is the contents of the search box:
$(this).val();
//So you could perform a function here, like replacing the occurences of the
//search text with a span (you could use CSS to highlight the span with a
//background colour:
var html_contents = $("#search_area").html();
var search_tem = $(this).val();
$("#search_area").html(html_contents.replace(search_term, '<span class="highlight">'+search_term+'</span>'));
});
请注意,在上面的示例中,Javascript 的“替换”功能只会替换第一次出现的位置。您需要在第一个参数中使用正则表达式来替换所有。但我不想为您编写所有代码;)
关于html - Web 浏览器如何实现文本搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5433372/