javascript - 每次页面加载时用 javascript 突出显示文本

标签 javascript html css

我要实现的目标:

在线 应显示为绿色,而离线 应显示为黄色。每次加载我的网页时。

我做了什么:我整天都在谷歌上搜索这个,甚至在 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 输入框和绿色在线和黄色离线字样的情况下自动发生。

提前致谢。

最佳答案

您可以使用这种方法:

<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 - 每次页面加载时用 javascript 突出显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38588721/

相关文章:

javascript - JQuery 用户界面 : dropping an item out of Sortable on a non-Sortable

javascript - 更高级的 TODO 列表,javascript

javascript - 我的页面上的代码阻止页面上的代码运行

html - SVG 在 DOM 中使用时不加载外部 CSS

html - 如何在css中的一定宽度后换行

css - 评论作者姓名在 Chrome 中呈现得很好,但在 IE 8 中半空白

jquery - 查找鼠标当前指向的 html 元素的 font-family?

javascript - 按钮点击jquery后显示div

html - 悬停时 anchor 动画的CSS问题

css - 我应该如何使用 CSS 在我的图像上设置此标题?