jQuery 如何使用 JavaScript 突出显示 HTML 页面中出现的所有文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16251505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:47:51  来源:igfitidea点击:

How to highlight all text occurrences in a HTML page with JavaScript?

javascriptjqueryhtml

提问by Uwe Keim

I really thought this would have been answered years ago, still I did not find any solution:

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

I want to highlight (i.e. make a colored background) all occurrences of a (sub-)string on an entire HTML page, completely client-side with JavaScript.

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

Just as you would use Ctrl+Fto search inside Google Chrome: When entering the search term, it highlights all the substrings that match my entered term.

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

Personally, I would walk all elements of the DOM tree, doing some replaceof the search term with something like

就个人而言,我会遍历 DOM 树的所有元素,replace使用类似

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

But I think there must be some more effective way?

但我想一定有一些更有效的方法吗?

My question:

我的问题:

How to use JavaScript (or jQuery) to highlight all substring occurrences inside a HTML page?

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

采纳答案by Sachin

Replacing the content with <span>is also an option. There is one more option that you can try which is Jquery plugins. Hereis one of them.

替换内容<span>也是一种选择。您还可以尝试另一种选择,即 Jquery 插件。是其中之一。

You can use it like this

你可以像这样使用它

$('body').text().highlight('my text to highlight');

回答by Archonic

I struggled to find a robust text highlighter that duplicates the browsers ctrl+ ffunctionality for months. I've used a host of jQuery plugins. Some are better than others but none are capable of spanning HTML. Say you want to find text that includes a link - the browser can do it but no jQuery plugins I've found can.

我一直在努力寻找一个强大的文本荧光笔,它可以重复浏览器ctrl+f功能长达数月之久。我使用了大量 jQuery 插件。有些比其他的要好,但没有一个能够跨越 HTML。假设您想查找包含链接的文本 - 浏览器可以执行此操作,但我发现没有任何 jQuery 插件可以执行此操作。

Turns out bare naked javascript has the answer. Just window.find().

原来裸露的javascript有答案。只是window.find()

find(string, matchcase, searchBackward)

string : The text string for which to search.

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

matchcase : Boolean value. If true, specifies a case-sensitive search. If you supply this parameter, you must also supply backward.

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

searchBackward : Boolean. If true, specifies a backward search. If you supply this parameter, you must also supply casesensitive.

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

It highlights html laden strings and it's compatible with every browser you care about. Read more about it at http://www.w3resource.com/javascript/client-object-property-method/window-find.php

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

The unfortunate thing is you can't seem to do anything with it. I can't wrap it in styled span tags, get the position, scroll to it or change the highlight colour. I'm still looking for the ideal ctrl+ fJS function.

不幸的是,你似乎无法用它做任何事情。我无法将它包裹在样式化的跨度标签中,无法获取位置、滚动到它或更改突出显示颜色。我还在寻找理想的ctrl+ fJS功能。

回答by Yuci

Window.find()should do the job.

Window.find()应该可以完成这项工作。

Although it is not standardised yet, almost all major newer-version browsers support it, such as Google Chrome, Firefox, IE, Safari, Opera, and browsers on iPhone/Android/Amazon Fire tablets and phones, etc.

虽然还没有标准化,但几乎所有主流的新版本浏览器都支持它,比如谷歌 Chrome、火狐、IE、Safari、Opera,以及 iPhone/Android/Amazon Fire 平板电脑和手机上的浏览器等。

Below is a sample implementation:

下面是一个示例实现:

/*
 * 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";
    }
}

The code is from Tim Down' implementation using Window.find()

代码来自 Tim Down使用 Window.find() 的实现

Before the search, the HTML text looks like:

在搜索之前,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>

Once you've search for text, for example, some lápices in it, and some formatting bits, and a URL Google, the HTML text will change to:

例如,搜索文本后,some lápices in it, and some formatting bits, and a URL GoogleHTML 文本将更改为:

<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>

See the code on jsfiddle.

请参阅jsfiddle 上的代码

回答by naquiuddin

If you are trying to highlight the search terms from google then you can use this jquery plugin available at https://github.com/hail2u/jquery.highlight-search-terms

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

If you want functionality like chrome. you can use this code.

如果你想要像 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(){
          return "<span style='background-color: red;'>" +  + "</span>"
        });

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

回答by Williham Totland

The best option for doing this is usually, somewhat surprisingly, to notdo it.

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

Rely instead on the built-in search feature of the web browser: This ensures that users have a consistent experience, and saves you a lot of trouble in having to double the work that has already been done to allow for this.

而是依靠 Web 浏览器的内置搜索功能:这可确保用户获得一致的体验,并为您省去很多麻烦,因为您必须将已经完成的工作加倍以实现这一目标。