使用html中的按钮使用外部Javascript文件执行事件

时间:2019-03-01 02:57:14

标签: javascript

基本上,我已被分配一个任务来创建一个外部Javascript代码文件,以与我的讲师已经创建的html代码文件相对应:

我应该使html代码中列出的按钮更改框图形:“ button1”增大框; “ button2”使框变成蓝色; “按钮3”使盒子的颜色淡出;和“ button4”将框重置为其原始大小和颜色。

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

});

$("#button2").on("click", function() {
  $("#box").animate().css({
    backgroundColor: "blue"
  });

});

$("#button3").on("click", function() {
  $("#box").fadeOut();

});

$("#button4").on("click", function() {
  $("#box").fadeIn("fast").animate({
      height: "150px",
      weight: "150px"
    },
    "fast").css({
    backgroundColor: "orange"
  });

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!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="button1">Grow</button>
  <button id="button2">Blue</button>
  <button id="button3">Fade</button>
  <button id="button4">Reset</button>


</body>

</html>

我正在阅读各种冲突的方式来创建此Javascript代码。我是否缺少使这些按钮正常工作的“ getElementById”功能?还是其他功能? 请帮忙!并预先感谢!

1 个答案:

答案 0 :(得分:0)

您的代码中只有一个小错误。

$("#button4").on("click", function() {
$("#box").fadeIn("fast").animate({
    height: "150px", 
    weight: "150px"}, // spelling mistake?
    "fast").css({
        backgroundColor: "orange"; // this is the error
    });
})

删除;,它可以正常工作:

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

});

$("#button2").on("click", function() {
$("#box").animate().css({
    backgroundColor: "blue"
});

});

$("#button3").on("click", function() {
$("#box").fadeOut();

});

$("#button4").on("click", function() {
	$("#box").fadeIn("fast").animate({
    height: "150px", 
    width: "150px"}, 
    "fast").css({
        backgroundColor: "orange"
    });
})
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
	<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>