【问题标题】:How can i add more than one colored text styles to my javascript code?如何在我的 javascript 代码中添加一种以上的彩色文本样式?
【发布时间】:2022-10-05 02:39:56
【问题描述】:
let combo = document.getElementById("string_determine");
let div = document.getElementById("mybox");
// I'm learning javascript. I would like to be able to add multiple colored text in my javascript. I would like the "This is black" text to be in black color and "This is blue" to be in blue color. As currently they both display as blue.
let string_determine;
switch(combo.options[combo.selectedIndex].text){
case '"blueblue"':
string_determine = "This is black" + "This is blue"; div.style.color = "blue"; break;
【问题讨论】:
标签:
javascript
text
styles
【解决方案1】:
不需要 switch 语句。您可以尝试使用具有所需颜色的样式属性的 span 元素围绕文本:
function setTextColor(element, text, color) {
const elementContent = element.innerHTML;
if (elementContent.search(text) !== -1) {
const coloredElement = `<span style="color: ${color}">${text}</span>`;
const newElementContent = elementContent.replace(text, coloredElement);
element.innerHTML = newElementContent;
} else {
console.error(`Cannot find text "${text}" in the given element`);
}
}
const combo = document.getElementById("string_determine");
// Text Element | Text to Stylize | Color (Any format of color supported in CSS)
// ----- ------------- -----
setTextColor(combo, "This is red", "red");
setTextColor(combo, "This is green", "#00ff00");
setTextColor(combo, "This is blue", "rgb(0, 0, 255)");