jQuery animate()方法
animate()方法是jQuery中的一个内置方法,用于改变元素的CSS样式状态。这个方法也可以用来改变CSS属性,为选定的元素创建动画效果。
语法:
(selector).animate({styles}, para1, para2, para3);
这里的 “选择器 “是指选定的元素。
参数:它接受四个参数,具体如下–**
- styles。它有助于设置新的CSS属性。
- para1:这是一个可选参数,用于设置参数的速度,其默认值为400毫秒。
- para2:这是可选的,这指定了元素在不同位置的速度。
- para3:这是一个可选的功能,用于在动画完成后执行。
返回值:它返回通过使用上述方法所做的改变。
例子1:在这个例子中,参数没有被传递给这个方法。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!--jQuery code to show animate() method-->
<script>
(document).ready(function () {
("#b1").click(function () {
("#box").animate({
width: "300px"
});
("#box").animate({
height: "300px"
});
});
});
</script>
<style>
div {
width: 100px;
height: 100px;
background-color: green;
}
#b1 {
margin-top: 10px;
}
</style>
</head>
<body>
<div id="box"></div>
<!-- click on this button -->
<button id="b1">Click Here !</button>
</body>
</html>
输出:
例子2:在这个例子中,所有的参数都被传递到这个方法。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://code.jquery.com/jquery-1.10.2.js">
</script>
<style>
div {
background-color: green;
height: 100px;
width: 100px;
margin-top: 10px;
}
#b1 {
margin-top: 10px;
}
</style>
</head>
<body>
<div id="box"></div>
<!-- click here and animation will start -->
<button id="b1">Click Here !</button>
<!-- jQuery code to show the animate method -->
<script>
(document).ready(function () {
("#b1").click(function () {
("#box").animate({
height: "200px",
width: "200px"
}, {
duration: 1000,
easing: "linear",
complete: function () {
(this).after(
"<p>Reaches to maximum height and width !</p>");
}
});
});
});
</script>
</body>
</html>
输出: