如何更改 div 中包裹的字符串的特定部分的颜色:
我们有一个这样的 div:
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>
我们如何使用下面的代码模板将“可信在线社区”部分的颜色更改为红色?
let text = document.getElementById("text");
// We want to only change the color of this portion of the text
changeColor('trusted online community');
function changeColor(portion){
// code to change the text color
...
// function to animate the color from black to red
function changeToRed(el) {
el.classList.add("colorRed");
}
};
.colorRed {
animation: colorRedAnime 0.8s cubic-bezier(0.785, 0.135, 0.15, 0.86);
animation-fill-mode: forwards ;
}
@-webkit-keyframes colorRedAnime {
from { color: #808080 }
to { color: #e80000 }
}
<div class="container">
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>
</div>
最佳答案
您需要创建一个SPAN
并将其添加到(内部)html
var lookFor = 'trusted online community';
var idx = text.innerHTML.indexOf(lookFor); //you could use regex also as an alternative
text.innerHTML = text.innerHTML.substring(0, idx) + '<span class="colorRed">' + lookFor + '</span>' + text.innerHTML.substring(idx + lookFor.length);
关于javascript - 更改 div 中包裹的字符串特定部分的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60007856/