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链接错了吗?
要访问backgroundColor
you需要访问元素的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>