DIV CSS 佈局教程網

jQuery animate 動畫方法詳解與使用示例
編輯:JQuery特效代碼     

animate() 是 jQuery 中用於創建自訂動畫的核心函數。本文由基礎用法講到參數含義,並附上多個實用示例。

基礎示例

點擊按鈕讓方塊放大、文字變大,並搭配漸變速度與 easing:

$(function() {
$("#left").click(function(){
$(".block").show();
$(".block").animate({
width: "+200px",
height: "+200px",
fontSize: "1em",
borderWidth: 10
}, "slow", "swing");
});
$("#right").click(function(){
$(".block").show();
$(".block").animate({
width: "-200px",
height: "-200px",
fontSize: "10em",
}, "slow", "swing");
});
// 先漸隱,後顯示
$("p").animate({ opacity: 'toggle' }, "slow", "swing");
$("p").animate({ opacity: 'show' }, 500, function() { alert('加載完成'); });
});

方法簽名與參數

$(...).animate(params, [duration], [easing], [callback])
  • params:一組包含作為動畫屬性與終值的樣式物件,屬性名要用駝峰式(如 marginLeft 而非 margin-left)。
  • duration(可選):三種預定速度的字串("slow"、"normal"、"fast")或毫秒數值。
  • easing(可選):擦除效果名稱,預設提供 "linear" 與 "swing"。
  • callback(可選):動畫完成時執行的函數。

更多示例

同時套用多種效果:

$("#go").click(function(){
$("#block").animate({
width: "90%",
height: "100%",
fontSize: "10em",
borderWidth: 10
}, 1000 );
});

讓元素左右相對移動:

$("#right").click(function(){ $(".block").animate({left: '+50px'}, "slow"); });
$("#left").click(function(){ $(".block").animate({left: '-50px'}, "slow"); });

切換高度與透明度:

$("p").animate({ height: 'toggle', opacity: 'toggle' }, "slow");

在 500 毫秒內移到 left 為 50 並完全顯示:

$("p").animate({ left: 50, opacity: 'show' }, 500);

補充:animate 中的屬性值可使用 +=/-= 做相對運動,也可使用 em 與 % 單位;若 duration 設為 0 則動畫直接完成。自訂 easing(如 "easein")則需額外引入 easing 插件才會生效。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved