【问题标题】:Using getElementById() with bgcolor attribute使用带有 bgcolor 属性的 getElementById()
【发布时间】:2017-10-14 10:29:23
【问题描述】:
为什么这段代码不起作用?
<!DOCTYPE html>
<html>
<head>
<title> Home </title>
</head>
<body id = "b" bgcolor = "lightblue">
<button onclick = "document.getElementById('b').bgcolor = 'lightgreen'"> Light Green </button>
</body>
</html>
我尝试更改正文标签中的文本属性值,它可以工作,但由于某种原因它不适用于 bgcolor 并且背景仍然具有浅蓝色。
【问题讨论】:
标签:
javascript
html
css
web
【解决方案1】:
样式是通过.style.backgroundColor 设置的(有关style object 的详细信息,请参阅MDN)。 bgcolor 作为一个属性已经过时了十多年,反映的属性是 bgColor(大小写很重要)。
所以:
document.getElementById("b").style.backgroundColor = 'lightgreen';
不过,一般来说,将演示文稿与标记混合并不理想。相反,请考虑添加/删除您使用 CSS 设置样式的类,例如:
document.getElementById("b").classList.add('clicked');
...与
.clicked {
background-color: lightgreen;
}
...在您的样式表中。
(classList 在现代浏览器中得到很好的支持,并且有一个适用于过时浏览器的 polyfill;更多 on MDN。)