web前端 -- jQuery -- jQuery里设置动画的4种方式
根据千峰教育学习视频所练习的笔记 | 学习一段时间,我也有写一点东西的必要了···

根据这张图,不难看出今天的内容是讲动画。
1. jQuery给我们提供了4种制作动画的方式:
制作动画的方式 | 说明 |
---|---|
show / hide | 默认情况下是没有动画的,调用某元素的show/hide 时候会直接显示/隐藏。当 show 和 hide 中传递了数字,我们我们要以固定时间来进行 show/hide ,这个时候才会有动画效果 |
fadeIn / fadeOut | fade意思是褪色,实际上就是改变元素透明度效果。fadeIn 将元素显示出来,进入页面,fadeOut将元素调出页面。 |
slideDown / slideUp | 像拉动卷帘门一样来显示/隐藏 |
animate / stop | 改变元素宽高来进行动画设置/停止动画 |
2. 实现动画效果:
2.1. show/down
- 在页面设置一个 div,设置 div 样式,添加显示、隐藏按钮
<style type="text/css">
div{
width: 200px;
height: 200px;
background: #87CEEB;
}
</style>
<body>
<button>显示</button>
<button>隐藏</button>
<div></div>
<script src="jquery-3.4.1.min.js"></script>
<script>
$('button:first').click(function(){
$('div').show(4000); //选中div,并且调用show
});
$('button:last').click(function(){
$('div').hide(4000);
});
</script>
</body>
 
- 可以看到点击隐藏/显示,宽高透明度同时变化,将div隐藏/显示
2.2. fadeIn / fadeOut
- 只需要改变上头的动画函数
<script>
$('button:first').click(function(){
$('div').fadeIn(4000);
});
$('button:last').click(function(){
$('div').fadeOut(4000);
});
</script>
 
- 点击隐藏/显示,只改变透明度
2.3. slideDown / slideUp
- 同理
<script>
$('button:first').click(function(){
$('div').slideDown(4000);
});
$('button:last').click(function(){
$('div').slideUp(4000);
});
</script>

- 点击隐藏/显示,拉窗帘方式
2.4. animate / stop
2.4.1 设计animate动画
<script>
$('button:first').click(function(){
$('div').animate({
//第一个参数:要改变的属性,可以是多个属性
width:400,
height:400
});
})
$('button:last').click(function(){
$('div').animate({
width:100,
height:100
})
})
</script>
 
- 我们回页面上操作,发现是同时等比例改变宽、高和透明度。如果我想先改变其中一个属性再改变另一个属性,可以这样做:
```html
```

- 通过animate演示,我们可以知道调用一个元素的动画函数的时候,都会为元素添加动画队列,并且每调用一次函数,队列中就添加一个动画事件。当其中的一个动画事件结束才开始下一个动画
2.4.2. 停止动画
- 先添加一个停止动画的按钮
<button>停止动画</button>
- 设置停止
<script>
$('button:first').click(function(){
$('div').animate({
width:500
},4000 ).animate({
height:600
},4000);
});
$('button:eq(1)').click(function(){
/*子元素选择器只有:first和:last,第一个和最后一个。需要选取中间的子元素使用eq(index);index是子元素数组的下标*/
$('div').animate({
height:200
},4000).animate({
width:200
},4000);
});
$('button:last').click(function(){
$('div').stop();
</script>
- 回到页面操作,发现停止的是当前队列正在执行的动画,不影响下一次动画
- 如果我要停止全部动画,可以将stop()参数传入true