javascript - 淡出和重置按钮对 Javascript 和 HTML 文件没有响应
问题描述
我想透露一下,我对这一切都非常陌生,对术语等了解很少。我为我的课程分配了预习,它指示我“使用 JavaScript 在按钮单击时更改框的 CSS 属性” .
我设法使“增长”和“蓝色”按钮工作,但其他两个没有反应。我正在使用 VS 代码。对于我的代码中的任何问题,我将不胜感激。谢谢!
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>
解决方案
三个问题:
- 一个错字:
document,getElementById
有一个逗号而不是一个点。 - “lightOrange”不是有效的颜色名称。如果您不想使用十六进制或 rgb 代码,可以参考此处支持的名称:https ://www.w3schools.com/cssref/css_colors.asp (但从长远来看,您可能会更快乐地学习十六进制代码;颜色的名称充其量是不一致的。)
- 您的第四个函数有一个明显的复制粘贴错误
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>
推荐阅读
- apache-spark - spark-cassandra-connector,将重试尝试限制为死 cassandra 节点
- angular - 如何通过使用 HostListener 在 Angular 8 中关闭浏览器来调用事件或 API,
- java - CrudRepository.findOne(null) 返回 Null
- python - Pyodbc python读取SQL存储过程中未提交的数据
- c# - 我可以创建异常发生的方法吗?
- javascript - Express js 卡在一页上
- laravel - axios.get /airlock/csrf-cookie 在 laravel 7 中不生效
- objective-c - 在swift中使用grpc“套接字未连接”
- c - C 程序 Pig 拉丁语翻译错误 - 如何修复错误?
- python - ImportError:没有名为 scapy.all 的模块