如何使用jQuery创建左右滑动的切换效果
这里的任务是在JQuery中创建一个左右滑动的切换效果,你可以使用jQuery的animate()方法。
.animate()方法:它是用来改变CSS属性,为所选元素创建动画效果的。
语法:
(selector).animate({styles}, para1, para2, para3);
步骤:
- 实际的箱体宽度被储存在变量中,其宽度值将被改变。
- .animate()方法接收要被动画化的选择器。
- 宽度样式属性是根据要求给定的值。
- width: 0 – 用于切换左侧。
- width:存储的前一个值 – 用于向右切换。
示例 1:
<!DOCTYPE html>
<html>
<head>
<title>How to create slide left and
right toggle effect using jQuery?</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<style type="text/css">
.box {
float: center;
overflow: hidden;
background: #32a852;
width: 400px;
padding: 0px;
}
/* Add padding and border to inner content
for better animation effect */
.box-inner {
width: 400px;
padding: 0px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>jQuery | How to create slide
left and right toggle effect?</h3>
<hr>
<div class="box">
<div class="box-inner">
<h4>.animate() method is used</h4>
<p>GEEKSFORGEEKS - A computer
science portal for geeks.</p>
</div>
</div>
<hr>
<button type="button" class="slide-left">
Click to Slide-Left
</button>
<button type="button" class="slide-right">
Click to Slide-Right
</button>
<script type="text/javascript">
(document).ready(function() {
var boxWidth =(".box").width();
(".slide-left").click(function() {
(".box").animate({
width: 0
});
});
(".slide-right").click(function() {
(".box").animate({
width: boxWidth
});
});
});
</script>
</center>
</body>
</html>
输出:
在点击按钮之前:
点击按钮后–“点击向左滑动”:
点击按钮后–“点击向右滑动”:
示例 2:
<!DOCTYPE html>
<html>
<head>
<title>How to create slide left and
right toggle effect using jQuery?</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<style type="text/css">
.box {
float: center;
overflow: hidden;
background: #32a852;
width: 400px;
padding: 0px;
}
/* Add padding and border to inner content
for better animation effect */
.box-inner {
width: 400px;
padding: 0px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>jQuery | How to create slide
left and right toggle effect?</h3>
<hr>
<div class="box">
<div class="box-inner">
<h4>.animate() method is used</h4>
<p>GEEKSFORGEEKS - A computer
science portal for geeks.</p>
</div>
</div>
<hr>
<input onclick="change()"
type="button"
class="slide-toggle"
value="Click to Slide-Left"
id="myButton1">
<script type="text/javascript">
(document).ready(function() {
(".slide-toggle").click(function() {
if (this.value == "Click to Slide-Left") this.value =
"Click to Slide-Right";
else this.value = "Click to Slide-Left";
$(".box").animate({
width: "toggle"
});
});
});
</script>
</center>
</body>
</html>
输出:
在点击按钮之前:
点击按钮后–“点击向左滑动”:
点击按钮后–“点击向右滑动”: