细说 jQuery 样式篇(二) - 动画效果
文章目录
除了使用 jQuery 内置的 hide,show,toggle 等方法来展现效果,还可以使用更为强大的 animate 方法来展现动画效果。
创建一个有背景色的 div:
<style>
div {
width: 100px;
height: 100px;
background-color: lightblue;
border: 1px solid #ccc;
}
</style>
<div></div>

添加 jQuery 方法如下:
$(function() {
$('div').animate({'height': 'hide'}, 'slow');
});
当页面载入后,div 会逐渐消失,动画效果如同直接使用 hide 方法。animate 的第一个参数为包含属性及其值的对象,第二个参数为时长。
两种形式
.animate() 方法有两种形式:
第一种形式有四个参数:
1.一个包含样式属性及值的对象
2.可选的时长参数
3.可选的缓动(easing)类型
4.可选的回调函数
第二种形式有两个参数:
1.一个属性对象
2.一个选项对象
多个属性添加动画效果
仍旧以上例中的 div 为例,我们可以同时对该 div 的多个属性添加动画效果,添加 jQuery 代码如下:
$('div').animate({'height': '+=100px', 'width': '+=100px'}, 'slow');
此时对 div 的 height 和 width 属性同时生效,div 扩大一倍。

动画排队效果
对多个属性添加动画效果时,如果我们希望效果具有先后顺序,即排队效果的话,可以使用 jQuery 连缀来实现。
同样是上例,修改 jQuery 代码如下:
$('div').animate({'height': '+=100px'}, 'slow')
.animate({'width': '+=100px'}, 'slow');//连缀
此时,div 的 height 属性先发生变化,width 属性随后发生变化。
queue 属性
这里使用 animate 方法的第二种形式来测试 queue 属性:
1.当 queue 值为 false 时
$('div').animate({'height': '+=100px'}, {duration: 'slow', queue: false})
.animate({'width': '+=100px'}, {duration: 'slow', queue: false});
此时,排队效果失效,div 的 height 和 width 属性变化同时发生。
2.当 queue 值为 true 时
$('div').animate({'height': '+=100px'}, {duration: 'slow', queue: true})
.animate({'width': '+=100px'}, {duration: 'slow', queue: true});
此时,排队效果生效,div 的 height 属性先发生变化,width 属性随后发生变化。
动画并发效果
当对多个元素应用动画效果时,这些效果是同时发生的,即并发的。举例如下:
<style>
#a {
width: 100px;
height: 100px;
background-color: lightblue;
border: 1px solid #ccc;
}
#b {
width: 100px;
height: 100px;
background-color: green;
border: 1px solid #ccc;
}
</style>
<div id="a"></div>
<div id="b"></div>

jQuery 代码如下:
$(function() {
$('#a').animate({'height': '+=100px'}, 'slow');
$('#b').animate({'height': '+=100px'}, 'slow');
});
此时页面载入后,id 为 a 和 b 的 div 的高度同时发生改变。

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论