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



作者:
...