我要实现的目标:
在线 应显示为绿色,而离线 应显示为黄色。每次加载我的网页时。
我做了什么:我整天都在谷歌上搜索这个,甚至在 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/