如何在 Javascript 中更改变量的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16532114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:02:24  来源:igfitidea点击:

How do I change the color of a variable in Javascript?

javascriptcolors

提问by Squirrl

Here is my code:

这是我的代码:

var hi = "hi"
document.write(hi)

hi.style.color="#ff0000";
document.write(hi)

Why won't it change colors? I keep getting "Cannot read property 'style' of undefined".

为什么不变色?我不断收到“无法读取未定义的属性‘样式’”。

回答by Adam Plocher

var hiis a string, not a DOM element, so you can't apply a style to it. I think what you're trying to go for is something like:

var hi是一个字符串,而不是 DOM 元素,因此您不能对其应用样式。我认为你想要的是这样的:

var hi = "<span style='color:#ff0000'>hi</span>";
document.write(hi);

Another option would be to create the element on the fly:

另一种选择是动态创建元素:

var mySpan = document.createElement('span');
mySpan.innerHTML = "hi";
mySpan.style.color = "#ff0000";
document.getElementsByTagName('body')[0].appendChild(mySpan);