简体   繁体   English

如何在我的 javascript 代码中添加多个彩色文本 styles?

[英]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");

// I'm learning javascript. // 我正在学习 javascript。 I would like to be able to add multiple colored text in my javascript.我希望能够在我的 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;

There is no need for switch statement.不需要 switch 语句。 You can try surrounding the text with a span element with a style property of the color you want:您可以尝试使用具有所需颜色的样式属性的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM