[英]How can i add more than one colored text styles to my javascript code?
let combo = document.getElementById("string_determine");
let div = document.getElementById("mybox");
// 我正在學習 javascript。 我希望能夠在我的 javascript 中添加多個彩色文本。 我希望“這是黑色”文本為黑色,“這是藍色”為藍色。 目前它們都顯示為藍色。
let string_determine;
switch(combo.options[combo.selectedIndex].text){
case '"blueblue"':
string_determine = "This is black" + "This is blue"; div.style.color = "blue"; break;
不需要 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 glue", "rgb(0, 0, 255)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.