Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

html - Highlight a text with javascript everytime page loads

What I am trying to achieve:

The word online should appear green while the word offline should appear yellow. Everytime my webpage loaded.

What I have done: I have have searched for this on google all day and even on stackoverflow. All I could find is;

<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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use this approach:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...