【问题标题】:Highlighting in a web browser through function and text extraction通过功能和文本提取在 Web 浏览器中突出显示
【发布时间】:2013-08-12 12:56:22
【问题描述】:

我正在做一个小项目,需要我在网络浏览器中突出显示。 javascript 或 java 中是否有任何库可以在 Web 浏览器中突出显示? 我想突出显示给定文本的某个单词或一大块单词。

我知道有一些类似的问题涉及到C#,但我只知道javascript和java。如果可能,请使方法尽可能简单。

【问题讨论】:

    标签: javascript browser web highlight highlighting


    【解决方案1】:

    以前有人问过这个问题。

    它应该会为你解答:How to highlight text using javascript

    【讨论】:

      【解决方案2】:

      也许来自jsFiddle 的代码很有用。荧光笔功能:

      function highLight(term,root,forElements,styleclass){
          root = root || document.querySelector('body');
          term = term instanceof Array ? term.join('|') : term;
      
          if (!term) {
           throw TypeError('Highlighter needs a term to highlight anything');
          }
      
          forElements = forElements && forElements instanceof Array 
                          ? forElements.join(',') 
                          : /string/i.test(typeof forElements) ? forElements : '*';
          styleclass = styleclass || 'highlight';
      
          var allDiv = root.querySelectorAll(forElements),
              re = RegExp(term,'gi'),
              highlighter = function(a){
                             return '<span class="'+styleclass+'">'+a+'</span>'
                            };
      
          for (var i=0; i<allDiv.length; i+=1){
              // recurse children
              if (allDiv[i].querySelectorAll(forElements).length){
                  highLight.call(null,term, allDiv[i],forElements,styleclass);
              }
              // replace term(s) in text nodes
              var node = allDiv[i];
              for (node=node.firstChild; node; node=node.nextSibling) {
                  if (node.nodeType===3){
                      var re = RegExp(term,'gi');
                      node.data = node.data.replace(re,highlighter);
                  }
              }
          }
          //finally, replace all text data html encoded brackets
          root.innerHTML = root.innerHTML
                            .replace(/&lt;/gi,'<')
                            .replace(/&gt;/gi,'>');
      }
      

      【讨论】:

        猜你喜欢
        • 2010-09-19
        • 2014-01-07
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 2012-05-10
        • 2019-10-16
        • 2012-07-30
        • 2021-10-31
        相关资源
        最近更新 更多