我的Javascript没有执行将Box的背景颜色更改为蓝色。我的代码出了什么问题?

问题描述 投票:0回答:1

document.getElementById("button2").addEventListener("click", function(){
    document.getElementById("box").backgroundColor="blue";
});
<!DOCTYPE html>
<html>
<head>
    <title>Jiggle Into JavaScript</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

    

</body>
</html>

当我click按钮2时,它应该将盒子从橙色变为蓝色。我的javascript链接错了吗?

javascript html
1个回答
2
投票

要访问backgroundColoryou需要访问元素的style属性,因为它嵌套在它下面。

所以你需要做document.getElementById("box").style.backgroundColor="blue";

请参阅以下代码:

document.getElementById("button2").addEventListener("click", function(){
    document.getElementById("box").style.backgroundColor="blue";
});
<!DOCTYPE html>
<html>
<head>
    <title>Jiggle Into JavaScript</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

    

</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.