首页 > 解决方案 > 淡出和重置按钮对 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>

标签: javascripthtmlcss

解决方案


三个问题:

  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>


推荐阅读