【问题标题】:Highlight a text with javascript everytime page loads每次页面加载时使用 javascript 突出显示文本
【发布时间】:2021-08-31 13:38:51
【问题描述】:

我想要达到的目标:

online 一词应显示为绿色,而 offline 一词应显示为黄色。每次加载我的网页。

我做了什么:我整天都在谷歌上搜索这个,甚至在 stackoverflow 上。我只能找到;

<head>
<style>
  .found {
    color:red;
  }
</style>
</head>
<body>
  <input id="s">
  <div id="a">
    i am online he is offline.
  </div>
  <script id="jsbin-javascript">
    var s = document.getElementById('s');
    var div = document.getElementById('a'); 

    function changeNode(n, r, f) {
      f=n.childNodes; for(c in f) changeNode(f[c], r);
      if (n.data) {
        f = document.createElement('span');
        f.innerHTML = n.data.replace(r, '<span class=found>$1</span>');
        n.parentNode.insertBefore(f, n);
        n.parentNode.removeChild(n);
      }
    }
    //s.onkeyup
    s.onkeyup = function(){
      var spans = document.getElementsByClassName('found');
      while (spans.length) {
        var p = spans[0].parentNode;
        p.innerHTML = p.textContent || p.innerText;
      }
      if (this.value) changeNode(
        div, new RegExp('('+this.value+')','gi')
      );
    };
  </script>
</body>

因此,每当我在输入框中输入内容时,这些词都会突出显示。但是,我希望这种情况在没有 ant 输入框的情况下自动发生,并且单词 online 为绿色,offline 为黄色。

提前致谢。

【问题讨论】:

  • 为什么不将它们包装在 HTML 中的 span 中?
  • 可以使用javascript onload事件
  • 老实说,您目前拥有的解决方案并不适合您想要做的事情。正如@gcampbell 建议的那样,将它们拆分为元素会更好,样式化它们会是最好的。
  • 这可能会有所帮助 - stackoverflow.com/questions/8644428/…
  • 试试我的新答案

标签: javascript html css


【解决方案1】:

您可以使用这种方法:

<html>
 <head>
   <style>
     .green {
       color: green;
     }
     .red {
       color: red;
     }
  </style>
</head>
<body>
  <h1 id="colouredText">This is a green text, and here a red text</h1>
  <script>
    var text = document.getElementById("colouredText");
    var words = text.innerHTML.split(" ");
    for(var i = 0; i < words.length; i++) {
      if(words[i] == "red") {
        words[i] = "<span class='red'>" + words[i] + "</span>";
      }
      if(words[i] == "green") {
        words[i] = "<span class='green'>" + words[i] + "</span>";
      }
    }
    text.innerHTML = words.join(" ");
  </script>
</body>

【讨论】:

    【解决方案2】:

    这是一个普通的javascript:

    1. 循环遍历文档中的元素以查找段落;
    2. 将段落分解为以空格分隔的单词;
    3. 用样式span 替换onlineoffline 的每个实例;和
    4. 重建包含样式spans的段落

    var body  = document.getElementsByTagName('body')[0];
    
    for (var i = 0; i < body.childNodes.length; i++) {
        if (body.childNodes[i].nodeName !== 'P') {continue;}
    
        var textArray = body.childNodes[i].textContent.split(' ');
        body.childNodes[i].textContent = '';
    
        for (var j = 0; j < textArray.length; j++) {
    
            if (textArray[j] === 'online') {
                var online = document.createElement('span');
                var onlineText = document.createTextNode('online');
                online.appendChild(onlineText);
                online.classList.add('online');
                textArray[j] = online;
            }
    
            else if (textArray[j] === 'offline') {
                var offline = document.createElement('span');
                var offlineText = document.createTextNode('offline');
                offline.appendChild(offlineText);
                offline.classList.add('offline');
                textArray[j] = offline;
            }
    
            else {
                textArray[j] = document.createTextNode(textArray[j]);
            }
    
            body.childNodes[i].appendChild(textArray[j]);
    
            if (j < (textArray.length - 1)) {
                var space = document.createTextNode(' ');
                body.childNodes[i].appendChild(space);
            }
        }
    }
    .online {
    color: rgb(0,255,0);
    }
    
    .offline {
    color: rgb(255,255,0);
    }
    <p>upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline upline downline inline outline underline overline online offline upline downline inline outline underline overline</p>
    
    <p>underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline underline overline online offline upline downline inline outline</p>

    【讨论】:

      【解决方案3】:

      我不明白你为什么需要 Javascript 来完成这样的事情。至少按照你解释的方式。

      为什么你不能像这样使用纯 html 来做到这一点:

      <div id="a">
          i am <span style="color:green">online</span> he is <span style="color:yellow">offline</span>.
      </div>
      

      这是JSfiddle

      如果这有帮助,请告诉我。

      【讨论】:

      • &lt;text&gt; 是 HTML 元素吗?
      • @Rounin 非常正确,我使用的是 razor 引擎,但 &lt;text&gt; 块的 razor sn-p。好接。编辑不当
      【解决方案4】:

      在包含 Jquery 后尝试使用它。或者在你喜欢的时候调用 startHighlightProcess 方法。

      $(document).ready(function(){
      startHighlightProcess("online","onlineClass");
      startHighlightProcess("offline","offlineClass");
      });
      
      function startHighlightProcess(keywordToHighlight,classname)
      var searchedKeyword = keywordToHighlight;
      var newClassToSet = classname;
              function startHighlighting() {                
                          highlightWord(document.body, searchedKeyword.toLowerCase());
                  };
      
      
      
                  function highlightWord(root, word) {
      var classToSet = newClassToSet;
                      textNodesUnder(root).forEach(highlightWords);
      
                      function textNodesUnder(root) {
                          var walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false),
                              text = [], node;
                          while (node = walk.nextNode()) text.push(node);
                          return text;
                      }
      
                      function highlightWords(n) {
                          for (var i; (i = n.nodeValue.toLowerCase().indexOf(word, i)) > -1; n = after) {
                              var after = n.splitText(i + word.length);
                              var highlighted = n.splitText(i);
                              var span = document.createElement('span');
                              span.className = classToSet;
                              span.appendChild(highlighted);
                              after.parentNode.insertBefore(span, after);
                          }
                      }
                  }
      

      【讨论】:

        【解决方案5】:

        JQuery - 定位所有满足过滤器的段落

        var textToFind = 'online';
        
        $("p:contains('" + textToFind + "')").each(function (i, element) {
            // extract the element content
            var content = $(element).text();
        
            // replace the text to find with the new mark up
            content = content.replace(textToFind, '<span class="highlight">' + textToFind + '</span>');
        
            // put back into the element
            element.html(content);
        });
        

        请注意,这将用新内容替换段落的内容,如果有任何与段落中的元素相关联的处理程序,它们将丢失。

        谨慎使用。

        【讨论】:

          【解决方案6】:

          实际上,有一种非常简单的新方法可以做到这一点。

          只需添加#:~:text=Highlight%20These

          尝试访问此链接

          https://stackoverflow.com/questions/38588721#:~:text=Highlight%20a%20text

          注意:仅适用于 chrome :(

          【讨论】:

          • 这在 Firefox 中不起作用。不过会很酷!
          • 是的,很遗憾。在我评论这篇文章几个月后,我也发现了。
          猜你喜欢
          • 2021-12-01
          • 1970-01-01
          • 2017-01-20
          • 2013-04-07
          • 1970-01-01
          • 1970-01-01
          • 2015-06-17
          • 1970-01-01
          • 2016-04-09
          相关资源
          最近更新 更多