Using getElementById() with bgcolor attribute

Why this code doesn't work?

<!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>

I tried to change text attribute value in the body tag and it works, but for some reason it doesn't work with the bgcolor and the background still has the lightblue color.


The style is set via .style.backgroundColor (see MDN for details on the style object). bgcolor as an attribute has been obsolete for well over a decade, and the reflected property was bgColor (case is significant).

So:

document.getElementById("b").style.backgroundColor = 'lightgreen';

Generally, though, mixing presentation with markup isn't ideal. Instead, consider adding/removing a class that you style with CSS, eg:

document.getElementById("b").classList.add('clicked');

...with

.clicked {
    background-color: lightgreen;
}

...in your stylesheet.

( classList is well-supported in modern browsers, and there's a polyfill for obsolete browsers; more on MDN.)

链接地址: http://www.djcxy.com/p/15372.html

上一篇: 如何使用storyboard将UITableView添加到多个子视图中的一个

下一篇: 使用getElementById()和bgcolor属性