语法
$(selector).animate(stylesObj,[duration],[timing-function],[callback])
参数
- stylesObj:要执行动画的 CSS 属性与它设定的终点值组成的对象
- duration:执行动画时长,值为三种预定速度之一的字符串(“slow”、”normal”、”fast”)或表示动画时长的毫秒数值(可选)
- timing-function:动画运动速率函数,只有两个值: swing 和 linear(可选)
- callback:动画执行完后立即执行的回调函数(可选)
动画设定样式终点值时也可以不带单位。
示例:
<style>
.box{
position: absolute;
top: 50px;
left: 50px;
width: 150px;
height: 150px;
background-color: #f00;
}
</style>
<body>
<div class="box"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var $box = $(".box");
$box.click(function (){
// 样式值可以带单位,也可以不带单位
$(this).animate({
top: "150px",
left: 150,
width: 300,
height: 300,
opacity: .2
}, 2000, "swing", function(){
console.log("动画执行完成");
})
})
</script>
</body>