gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:22:34 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com