淡入淡出和重置按钮在 Javascript 和 HTML 文件上没有响应



我想说的是,我对这一切都非常陌生,对术语等也知之甚少。我的课前作业是教我"使用JavaScript在点击按钮时改变一个框的CSS属性"。

我已经成功地使"成长"了。和";blue"按钮可以工作,但其他两个没有反应。我使用VS Code。对于我的代码中的任何问题,我都很感激任何简单的解释。谢谢!

document.getElementById("growBtn").addEventListener("click", function(){document.getElementById("box").style.height = "250px"});
document.getElementById("blueBtn").addEventListener("click", function(){document.getElementById("box").style.backgroundColor = "blue" });

document.getElementById("fadeBtn").addEventListener("click", function(){document,getElementById("box").style.backgroundColor = "lightOrange" });
document.addEventListener("resetBtn").addEventListener("click", function(){document.getElementById("box").style.height = "150px"});
<!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> -->
</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="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>
<script type="text/javascript" src="javascript.js"></script>

</body>
</html>

三个问题:

  1. 一个错字:document,getElementById用逗号代替点。
  2. "lightOrange"不是有效的颜色名称。如果你不喜欢使用十六进制或rgb代码,这里有一个支持名称的参考:https://www.w3schools.com/cssref/css_colors.asp(但从长远来看,你可能会更喜欢学习十六进制代码;颜色的命名最多不一致)
  3. 你的第四个函数有一个明显的复制粘贴错误,用addEventListener代替getElementById

修正版:

document.getElementById("growBtn").addEventListener("click", function() {
document.getElementById("box").style.height = "250px"
});
document.getElementById("blueBtn").addEventListener("click", function() {
document.getElementById("box").style.backgroundColor = "blue"
});
document.getElementById("fadeBtn").addEventListener("click", function() {
document.getElementById("box").style.backgroundColor = "peachpuff"
});
document.getElementById("resetBtn").addEventListener("click", function() {
document.getElementById("box").style.height = "150px"
});
<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="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>

最新更新