[英]Change color of specific part of element string in JavaScript
I'm creating a chat application, and I want the users text's to be colored.我正在创建一个聊天应用程序,我希望用户文本被着色。 Here is how I create the text element:
这是我创建文本元素的方式:
var item = document.createElement('li');
item.textContent = `[Anye]: hello`;
item.style.fontWeight = 'bold';
item.style.color = 'red';
This is how this code is executed:这是这段代码的执行方式:
This, on the other hand, is what I would want:另一方面,这就是我想要的:
Is there a way that I can change the color of only part of the text?有没有办法只改变部分文本的颜色?
Note: The desired image was created using the console, and please keep in mind that the messages are not fixed, it's up to the user what they want to say.注意:所需的图像是使用控制台创建的,请记住,消息不是固定的,取决于用户他们想说什么。
I'm willing to use jQuery
for this example, if needed.如果需要,我愿意在这个例子中使用
jQuery
。
Thanks!谢谢!
You can wrap the author in a span
element and set style property.您可以将作者包装在
span
元素中并设置样式属性。
var item = document.createElement('li'); item.style.fontWeight = 'bold'; const author = document.createElement("span"); author.innerText = "[Anye]: "; author.style.color = 'red'; item.append(author); item.innerHTML += "hello"; document.body.append(item);
Or you can wrap the message in a span
element and set a predefined style in CSS.或者您可以将消息包装在
span
元素中并在 CSS 中设置预定义样式。
var item = document.createElement('li'); item.innerHTML = `[Anye]: <span>hello</span>`; item.style.fontWeight = 'bold'; item.style.color = 'red'; document.body.append(item);
li span { color: initial; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.