每次页面加载时都使用javascript突出显示文本 [英] Highlight a text with javascript everytime page loads

查看:73
本文介绍了每次页面加载时都使用javascript突出显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的目标:

在线一词应显示为绿色,而离线一词应显示为黄色.每当我的网页加载时.

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

我做了什么:我整天都在Google上搜索过此内容,甚至在stackoverflow上也都搜索过.我只能找到的是

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>

因此,每当我在输入框中键入一些内容时,这些单词就会突出显示.但是,我希望这种情况不会自动发生,而无需使用ant输入框,而单词online会显示为绿色,而离线时会显示为黄色.

So whenever, I type something into the input box, the words become highlighted. However, I want this to happen automatically without ant input box and the word online in green and offline in yellow.

谢谢.

推荐答案

您可以使用以下方法:

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

这篇关于每次页面加载时都使用javascript突出显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆