006_动画
1. jQuery animate()方法
1.1. animate()方法執行CSS屬性集的自定義動畫。
1.2. 該方法通過CSS樣式將元素從一個狀態改變為另一個狀態。CSS屬性值是逐漸改變的, 這樣就可以創建動畫效果。
1.3. 只有數字值可創建動畫(比如: "margin:30px")。字符串值無法創建動畫(比如: "background-color:red")。
1.4. 語法1:
$(selector).animate(styles,speed,easing,callback);1.5. 參數
1.6. 語法2:
$(selector).animate(styles,options);1.7. 參數
2. jQuery animate()操作多個屬性
2.1. 請注意, 生成動畫的過程中可同時使用多個屬性:
$("button").click(function(){$("div").animate({left: '250px',opacity: '0.5',height: '150px',width: '150px'}); });2.2. animate()方法幾乎可以操作所有的CSS屬性。不過, 需要記住一件重要的事情: 當使用animate()時, 必須使用Camel標記法書寫所有的屬性名, 比如: 必須使用paddingLeft而不是padding-left; 使用marginRight 而不是margin-right等等。
2.3. 同時, 色彩動畫并不包含在核心jQuery庫中。
2.4. 如果需要生成顏色動畫, 您需要從jQuery.com下載Color Animations插件。
3. jQuery animate()使用相對值
3.1. 也可以定義相對值(該值相對于元素的當前值)。需要在值的前面加上+=或-=:
$("button").click(function(){$("div").animate({left: '250px',height: '+=150px',width: '+=150px'}); });4. jQuery animate()使用預定義的值
4.1. 您甚至可以把屬性的動畫值設置為"show"、"hide"或"toggle":
$("button").click(function(){$("div").animate({height:'toggle'}); });5. jQuery animate()使用隊列功能
5.1. 默認地, jQuery提供針對動畫的隊列功能。
5.2. 這意味著如果您在彼此之后編寫多個animate()調用, jQuery會創建包含這些方法調用的"內部"隊列。然后逐一運行這些animate調用。
5.3. 如果您希望在彼此之后執行不同的動畫, 那么我們要利用隊列功能:
$("button").click(function(){var div=$("div");div.animate({height: '300px', opacity: '0.4'}, "slow");div.animate({width: '300px', opacity: '0.8'}, "slow");div.animate({height: '100px', opacity: '0.4'}, "slow");div.animate({width: '100px', opacity: '0.8'}, "slow"); });6. 例子
6.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>jQuery動畫</title><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">$(document).ready(function(){$('#btn1').click(function(){$("div:visible").animate({left: '250px',opacity: '0.5',height: '150px',width: '500px'}, "slow", "swing");});$('#btn2').click(function(){$("div:visible").animate({left: '+=250px',opacity: '+=0.5',height: '+=150px',width: '+=500px'}, "normal", "swing");});$('#btn3').click(function(){$("div").animate({height: 'toggle'}, "fast", "swing");});$('#btn4').click(function(){var div = $("div:visible");// 使用$(selector).animate(styles,options);語法, callback函數無效div.animate({height:'+=100px', opacity: '0.5'}, {speed: 3000, easing: "linear"});div.animate({width:'+=100px', opacity: '0'}, {speed: 1000, easing: "linear"});div.animate({height:'+=100px', opacity: '0.5'}, {speed: 4000, easing: "linear"});div.animate({letterSpacing:'+=10px'}, {speed: 1000, easing: "linear", step: function(){console.log('動畫的每完成一步都會執行該函數');}, queue: true});});});</script></head><body><button id="btn1">animate操作多個屬性</button> <button id="btn2">animate使用相對值</button><button id="btn3">animate使用預定義的值</button> <button id="btn4">animate使用隊列功能</button><br /><br /><div style="background-color: red; width:400px; height: 50px; position: relative;">jQuery animate()方法允許您創建自定義的動畫。</div></body> </html>6.2. 效果圖
總結
- 上一篇: 005_滑动效果
- 下一篇: 007_停止动画或效果