javascript - 我的 Javascript 没有执行将框的背景颜色更改为蓝色。我的代码有什么问题吗?

标签 javascript html

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>

当我单击按钮2时,它应该将框从橙色变为蓝色。我的 javascript 链接是否错误?

最佳答案

要访问 backgroundColor,您需要访问元素的 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>

关于javascript - 我的 Javascript 没有执行将框的背景颜色更改为蓝色。我的代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49099269/

相关文章:

javascript - 在 Windows 10 机器上已经启动了一些其他 Node.js 文件后如何启动一个新的 Node.js 文件?

javascript - 在react js中添加子函数

Javascript - 如何删除一个对象?

jquery - Owl Carousel 2 个自定义点不可点击

css - css中div的动态宽度

html - FF 和 Chrome 之间的不同定位 div - HTML CSS

javascript - 使 Jquery 代码仅在元素在屏幕上时运行

javascript - PHP 解析 JSON 字符串

javascript - 保持图像的 3D 立方体在同一侧继续过渡

html - 电子邮件 HTML : How to keep relative same size on all devices?