javascript - 如何让我的重置按钮使用 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>
解决方案
要轻松重置内联样式,您可以使用$("#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");
});
推荐阅读
- php - 将代码从 php 转换为 twig 格式时出现空值错误
- c - 如何将整数加倍并更新它们?
- jquery - 在 Jquery 中使用不使用 html 的变量动态创建表
- c# - Office.Interop.Excel C#如何打开excel文件的流或base64
- ckeditor - 方程图像添加到两个编辑器,而不是单页中的一个 ckeditor
- javascript - 什么可能导致 socket.io 的服务时间很长?
- html - 将 div 移动到下一行
- c++ - 在 C++17 中计算具有 POD 类型的普通数组的字段?
- python-3.x - 没有名为“samlib”的模块
- mongodb - Mongodb查询一个字段依赖于另一个字段