【问题标题】:How to highlight all text occurrences in a HTML page with JavaScript?如何使用 JavaScript 突出显示 HTML 页面中出现的所有文本?
【发布时间】:2013-04-21 12:24:43
【问题描述】:

我真的以为这会在几年前得到回答,但我仍然没有找到任何解决方案:

我想在整个 HTML 页面上突出显示(即制作彩色背景)所有出现的(子)字符串,完全使用 JavaScript 在客户端。

就像您在 Google Chrome 中使用 Ctrl+F 搜索一样:输入搜索词时,它会突出显示与我输入的词匹配的所有子字符串。

就我个人而言,我会遍历 DOM 树的所有元素,对搜索词做一些 replace 之类的操作

<span style="background-color: yellow">MySearchTerm</span>

但我认为一定有更有效的方法?

我的问题:

如何使用 JavaScript(或 jQuery)突出显示 HTML 页面中出现的所有子字符串?

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

如果您想突出显示来自谷歌的搜索词,那么您可以使用https://github.com/hail2u/jquery.highlight-search-terms 上提供的这个 jquery 插件

如果您想要 chrome 之类的功能。您可以使用此代码。

$(document).ready(function(){
  var search = ['p', 'div', 'span'];

  $("#highlighter").bind('keyup', function(e){
    var pattern = $(this).val();

    $.each(search, function(i){
        var str = search[i];        
        var orgText = $(str).text();

        orgText = orgText.replace(pattern, function($1){
          return "<span style='background-color: red;'>" + $1 + "</span>"
        });

        $(str).html(orgText);
    });    
  });
});

【讨论】:

  • 我不会用这个。如果文本包含 HTML 代码,那么它将被注入而不转义。
【解决方案2】:

这样做的最佳选择通常是,有点令人惊讶的是,这样做。

转而依赖网络浏览器的内置搜索功能:这可确保用户获得一致的体验,并为您省去很多麻烦,因为您不得不将已经完成的工作加倍。

【讨论】:

  • 非常感谢。实际上,这是针对具有搜索字段的受限用户基础 Intranet 应用程序。我不会在公共场合这样做,对我们的用户来说,这似乎很有帮助:-)
  • @UweKeim:如果它是一个基于有限用户的应用程序,那就更有理由简单地教他们使用 Ctrl-F。 ;)
  • 然后他们必须搜索 两次,一次在 HTML 表单字段中,然后一次在浏览器中。我真的很想在第一次搜索后立即向他们展示匹配项。
  • @UweKeim:问题在于内置的搜索功能不仅仅是突出显示,它还可以跳转到下一个匹配项,以及其他类似的简洁功能。除非您也计划实施,否则用户最终会得到劣质产品,这是不好的。
  • @UweKeim:Google 还提供了一个非常简短的上下文摘录。
【解决方案3】:

几个月来,我一直在努力寻找能够复制浏览器 ctrl + f 功能的强大文本荧光笔。我使用了许多 jQuery 插件。有些比其他更好,但没有一个能够跨越 HTML。假设您想查找包含链接的文本 - 浏览器可以做到,但我发现没有 jQuery 插件可以做到。

原来裸露的 JavaScript 有答案。只需window.find()

find(string, matchcase, searchBackward)

string : 要搜索的文本字符串。

matchcase:布尔值。如果为 true,则指定区分大小写的搜索。如果你提供这个参数,你也必须向后提供。

searchBackward :布尔值。如果为真,则指定向后搜索。如果提供此参数,则还必须提供区分大小写。

它突出显示 html 负载的字符串,并且与您关心的每个浏览器兼容。在http://www.w3resource.com/javascript/client-object-property-method/window-find.php了解更多信息

不幸的是,您似乎无能为力。我无法将其包装在样式化的跨度标签中、获取位置、滚动到它或更改突出显示颜色。我还在寻找理想的 ctrl + f JS 函数。

【讨论】:

    【解决方案4】:

    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'implementation using 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>
    

    the code on jsfiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-02
      相关资源
      最近更新 更多