<分区>
标签 javascript html css
<分区>
出于某种原因,我无法设置 document.getElementById("id").style.color
的变量,因为它显然是“null”。为什么我每次需要设置颜色时都必须调用 document.getElementById("id").style.color
?
(我没有灯泡的图片,所以我决定即兴创作)
<html>
<head>
<title>Hello</title>
</head>
<body>
<pre id="light" onclick="toggleLight()">
____
/ __ \
/ // \
/ || \
| |
| |O |
\ O| /
\ || /
\ /
|~~~~|
|____|
**
</pre>
<script>
var on = false;
var bulb = document.getElementById("light").style.color;
function toggleLight(){
if(on==true){
bulb = "black";
on=false
} else if(on==false) {
bulb = "yellow";
on=true
}
}
</script>
</body>
编辑: 这个好像没说清楚。我编辑了代码,现在你可以试试了。你会明白我的意思。
最佳答案
您不能将颜色保存到变量然后更改它的原因是因为您只会更改变量。
但是你可以这样做:
var elem=document. getElementById("light");
然后在任何地方:
elem.style.color = "somecolor";
顺便说一下,我很喜欢这个灯泡。
关于Javascript - 为什么我不能将 style.color 设置为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19646355/
相关文章:
javascript - 如何获取一个对象的所有方法? [Javascript]
html - 定位 href 内的特定 div 以及所有用 main div 包裹的内容,以便在 css 中悬停
html - IE10 及更高版本 : is it possible to change the text-color of an select/option element?
html - 像 Google play 一样通过降级隐藏文本
javascript - 从不同的模块和 Controller 获取 Angular 变量
javascript - 初始化后更新 jQuery 插件设置