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

时间:2016-07-26 11:30:32

标签: 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>
&#13;
&#13;
&#13;

所以每当我在输入框中输入内容时,单词都会突出显示。但是,我希望在没有蚂蚁输入框的情况下自动进行此操作,并且在绿色和离线状态下以黄色显示在线状态。

提前致谢。

6 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

这是一个香草javascript:

  1. 遍历文档中的元素以查找段落;
  2. 将段落分成以空格分隔的单词;
  3. 使用样式span替换在线离线的每个实例;和
  4. 重新构建包含样式spans
  5. 的段落

    &#13;
    &#13;
    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);
            }
        }
    }
    &#13;
    .online {
    color: rgb(0,255,0);
    }
    
    .offline {
    color: rgb(255,255,0);
    }
    &#13;
    <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>
    &#13;
    &#13;
    &#13;

答案 2 :(得分:0)

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

为什么你不能像普通的html一样这样做:

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

这是JSfiddle

如果有帮助,请告诉我。

答案 3 :(得分:0)

在包含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);
                    }
                }
            }

答案 4 :(得分:0)

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);
});

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

小心使用。

答案 5 :(得分:0)

实际上,有一种非常简单且新颖的方法来实现此目的。

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

尝试访问此链接

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