使用带有 bgcolor 属性的 getElementById()

Posted

技术标签:

【中文标题】使用带有 bgcolor 属性的 getElementById()【英文标题】:Using getElementById() with bgcolor attribute 【发布时间】: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 并且背景仍然具有浅蓝色。

【问题讨论】:

为什么要使用已弃用的属性? Set the bgcolor attribute value的可能重复 【参考方案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。)

【讨论】:

以上是关于使用带有 bgcolor 属性的 getElementById()的主要内容,如果未能解决你的问题,请参考以下文章

匹配 TR 元素的 bgcolor 属性的 XPath 表达式

通过bgcolor属性选择元素

通过 bgcolor 属性选择元素

asp.net 文字控制 bgcolor

关于样式style

网页背景字体学习