如何在 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
How do I change the color of a variable in Javascript?
提问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 hi
is 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);