首页 > 解决方案 > 如何让我的重置按钮使用 JavaScript/JQuery 工作?

问题描述

我正在上一门编程课,我的一项任务是让一个盒子变大、变蓝、缩小和重置。我有前三个,但我不确定如何完成重置按钮。

$("#boxGrow").on("click", function() {
    $("#box").animate({height:"+=35px", width:"+=35px"}, "fast");
})

$("#boxShrink").on("click", function() {
    $("#box").animate({height:"-=35px", width:"-=35px"}, "fast");
})

$("#boxBlue").on("click", function() {
    $("#box").css("background-color", "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="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 class="btn" id="boxGrow">Grow</button>
    <button class="btn" id="boxBlue">Blue</button>
    <button class="btn" id="boxShrink">Fade</button>
    <button class="btn" id="boxReset">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

</body>
</html>

标签: javascript

解决方案


要轻松重置内联样式,您可以使用$("#box").removeAttr("style");,但这将删除元素上的所有内联 CSS。解决方案是将您的初始样式放在<style>标签中,因此您的代码将是:

<!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>
    <style>
      #box {
        height: 150px;
        width: 150px;
        background-color: orange;
        margin: 25px;
      }
    </style>
  </head>
  <body>
    <p>Press the buttons to change the box!</p>

    <div id="box"></div>

    <button class="btn" id="boxGrow">Grow</button>
    <button class="btn" id="boxBlue">Blue</button>
    <button class="btn" id="boxShrink">Fade</button>
    <button class="btn" id="boxReset">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

  </body>
</html>

$("#boxGrow").on("click", function() {
  $("#box").animate({ height: "+=35px", width: "+=35px" }, "fast");
});

$("#boxShrink").on("click", function() {
  $("#box").animate({ height: "-=35px", width: "-=35px" }, "fast");
});

$("#boxBlue").on("click", function() {
  $("#box").css("background-color", "blue");
});

$("#boxReset").on("click", function() {
  $("#box").removeAttr("style");
});

推荐阅读