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

gwbalxhn  于 2023-11-15  发布在  Java
关注(0)|答案(6)|浏览(140)

我努力实现的目标:

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>

字符串
因此,每当我在输入框中输入一些东西时,单词就会变得突出显示。然而,我希望这在没有蚂蚁输入框的情况下自动发生,单词在线用绿色,离线用黄色。
先谢了。

ebdffaop

ebdffaop1#

您可以使用此方法:

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

  </html>

字符串

xfb7svmp

xfb7svmp2#

下面是一个vanilla JavaScript:
1.循环遍历文档中的元素以查找段落;
1.将段落分成空格分隔的单词;
1.用样式化的span替换 onlineoffline 的每个示例;以及
1.重新构建包含样式化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>
0vvn1miw

0vvn1miw3#

事实上,有一个非常简单和新的方法来做到这一点。
只需添加#:~:text=Highlight%20These
尝试访问此链接
https://stackoverflow.com/questions/38588721#:~:text=Highlight%20a%20text
注意:仅适用于Chrome:(

jxct1oxe

jxct1oxe4#

我不明白为什么你需要JavaScript来完成这样的事情。嗯,至少在你解释的方式。
为什么你不能像这样用普通的html来做到这一点:

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

字符串
这是一个JSfiddle
如果有帮助就告诉我。

elcex8rz

elcex8rz5#

在你包含了Jquery.或者Just call the 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);
                    }
                }
            }

字符串

amrnrhlw

amrnrhlw6#

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

字符串
请注意,这将用新内容替换段落的内容,如果有任何与段落中的元素关联的处理程序,则这些处理程序将丢失。
请小心使用。

相关问题