细说 jQuery 样式篇(二) - 动画效果

除了使用 jQuery 内置的 hide,show,toggle 等方法来展现效果,还可以使用更为强大的 animate 方法来展现动画效果。
创建一个有背景色的 div

<style>
div {
  width: 100px;
  height: 100px;
  background-color: lightblue;
  border: 1px solid #ccc;
}
</style>
<div></div>

《细说 jQuery 样式篇(二) - 动画效果》

添加 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');

此时对 divheightwidth 属性同时生效,div 扩大一倍。

《细说 jQuery 样式篇(二) - 动画效果》

动画排队效果

对多个属性添加动画效果时,如果我们希望效果具有先后顺序,即排队效果的话,可以使用 jQuery 连缀来实现。
同样是上例,修改 jQuery 代码如下:

  $('div').animate({'height': '+=100px'}, 'slow') 
          .animate({'width': '+=100px'}, 'slow');//连缀

此时,divheight 属性先发生变化,width 属性随后发生变化。

queue 属性

这里使用 animate 方法的第二种形式来测试 queue 属性:
1.当 queue 值为 false

  $('div').animate({'height': '+=100px'}, {duration: 'slow', queue: false})
          .animate({'width': '+=100px'}, {duration: 'slow', queue: false});

此时,排队效果失效,divheightwidth 属性变化同时发生。
2.当 queue 值为 true

  $('div').animate({'height': '+=100px'}, {duration: 'slow', queue: true})
          .animate({'width': '+=100px'}, {duration: 'slow', queue: true});

此时,排队效果生效,divheight 属性先发生变化,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 样式篇(二) - 动画效果》

jQuery 代码如下:

$(function() {
  $('#a').animate({'height': '+=100px'}, 'slow');
  $('#b').animate({'height': '+=100px'}, 'slow');
});

此时页面载入后,idabdiv 的高度同时发生改变。

《细说 jQuery 样式篇(二) - 动画效果》

参考

http://book.douban.com/subject/24669823/

    原文作者:StephenLee
    原文地址: https://segmentfault.com/a/1190000000532283
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞