javascript - Javascript - 在div中,更改字符串中特定部分的颜色

如何更改div中字符串的特定部分的颜色:

有一个这样的div:


<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>



如何使用下面的代码,将'trusted online community'的颜色更改为红色?


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>

时间: 作者:

使用replace():

只需使用replace()方法查找和移除字符串的特定部分,并使用template literals向后添加相同的部分,但使用


const text = document.querySelector('#text');



const changeColor=(a,b)=> a.innerHTML = a.innerHTML.replace(b, `<span>${b}</span>`);



changeColor(text,"trusted online community");
span{color: red;}
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers </div>

在正规表达式中使用replace():

如果要替换特定部分的多个匹配项,可以使用正规表达式,如下所示:


const text = document.querySelector('#text');



const changeColor=(a,b)=> {


 let regexB = new RegExp(b,"g");


 a.innerHTML = a.innerHTML.replace(regexB, `<span>${b}</span>`);


}



changeColor(text,"trusted online community");
span {color: red;}
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers and Stack Overflow is the largest, most trusted online community for developers for a reason.</div>

使用split()和join():

另一种方法是在指定的分隔符字符串的每个实例上拆分字符串,在这种情况下,使用trusted online community方法,然后使用split()方法将字符串连接起来,<span>trusted online community</span>使用join()方法,如下所示:


const text = document.querySelector('#text');


const changeColor=(a,b)=> a.innerHTML = a.innerHTML.split(b).join(`<span>${b}</span>`);


changeColor(text,"trusted online community");
span {color: red;}
<div id="text" class="text-class">Stack Overflow is the largest, most trusted online community for developers.</div>

作者:

你需要创建一个SPAN,并将它添加到(inner)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);



作者:
...