[英]Javascript/jQuery change word color by specific some text contains
I have a simple question with jQuery Css.我有一个关于 jQuery Css 的简单问题。
I would like to change color of my text by specific word contains using jQuery.我想通过使用 jQuery 的特定单词来更改文本的颜色。
I have example like this:我有这样的例子:
<div class="me">I'm Groot</div>
How can I do that with jQuery or javascript?如何使用 jQuery 或 javascript 做到这一点?
You could replace all occurrences of your specific text snippets with custom styled html elements:您可以使用自定义样式的 html 元素替换所有出现的特定文本片段:
const yourName = "Groot";
const element = document.querySelector(".me");
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`)
.replace(yourName, `<span class="green-class">${yourName}</span>`);
Alternatively you can also make everything green except the I'm
like this:或者,您也可以将所有内容设为绿色,除了
I'm
这样的:
.me {
color: green;
}
element.innerHTML = element.innerHTML
.replace("I'm", `<span class="black-class">I'm</span>`);
This way not only Groot
is colored green but everything inside of the div
.这样,不仅
Groot
是绿色的,而且div
里面的所有东西都是绿色的。 That way your JavaScript doesn't need to know the name.这样您的 JavaScript 就不需要知道名称。
Just group them like so:像这样对它们进行分组:
<div class="me">I'm <span id="changer">Groot</span></div>
Then for CSS, style it like so:然后对于 CSS,将其设置为:
#changer {
color: green;
}
Then to change with javascript:然后用 javascript 更改:
document.getElementById("changer").innerHTML = "Changed";
Which of course you can add a setTimeout to change continuously当然你可以添加一个 setTimeout 来不断改变
Edit: No problem, since the only part changing is "Groot" part, So:编辑:没问题,因为唯一改变的部分是“Groot”部分,所以:
var changing = "Groot";
$('.me').text(`I'm <span id="changer">${changing}</span>`);
// then from here the value of the $('#changer') can be accessed and changed
$('#changer').text('Not Groot');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.