How to change the body's background color with buttons using javascript?

时间:2016-02-20 19:48:40

标签: javascript html

I'm attempting to change the entire background color of the body to the color that the button is assigned to. I'm new to javascript but I looked over the internet and my notes and couldn't find a problem. I think I'm just missing something very simple orrrrr i could be wayyy off.

THE HTML

<nav>
        <ul>
            <li>
                <button onclick="white()">
                    <p>White</p>
                </button>
            </li>
            <li>
                <button onclick="red()">
                    <p>Red</p>
                </button>
            </li>
            <li>
                <button onclick="yellow()">
                    <p>Yellow</p>
                </button>
            </li>
            <li>
                <button onclick="blue()">
                    <p>Blue</p>
                </button>
            </li>

        </ul>
    </nav>

THE JAVASCRIPT

function white() {
    document.body.backgroundColor("white");
}

function red() {
    document.body.backgroundColor("red");
}

function yellow() {
    document.body.backgroundColor("yellow");
}

function blue() {
    document.body.backgroundColor("blue");
}

3 个答案:

答案 0 :(得分:2)

backgroundColor是一个属性,而不是一个函数。它的style属性。将您的行更改为:

document.body.style.backgroundColor = "yellow"

此外,onClick属性有点过时了。您可以尝试使用JavaScript本身的事件处理程序(more information)。

答案 1 :(得分:1)

您有正确的想法,您只需要确保正确选择窗口的body元素:

document.querySelector('body').style.backgroundColor

所以你的功能看起来像是:

function white() {
    document.querySelector('body').style.backgroundColor = "white";
}
....

注意:

确保您将JavaScript放在网页的 end 上,它还没有!

答案 2 :(得分:1)

document.body.style.backgroundColor = "white"; // or any other color

有关MDNstyle媒体资源的详情。