為什麼連續寫好幾個 animate(),元素卻不是照我想要的順序動?答案就在 callback(回呼函數)。這個觀念一旦打通,動畫序列、非同步流程都能被你排得整整齊齊。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery callback 示範</title>
<script src="js/jquery.js"></script>
<style>
body{font-family:"微軟雅黑";width:980px;margin:0 auto;text-align:center;}
.box{width:300px;height:300px;background:green;border:1px solid #e6e6e6;
margin-top:50px;line-height:200px;position:absolute;}
button{border:none;background:green;width:100px;height:50px;line-height:50px;
color:#fff;font-size:16px;margin-top:50px;}
</style>
</head>
<body>
<button>點擊開始動畫</button>
<div class="box"></div>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $(".box");
div.animate({height:'200px', opacity:'0.4'}, "slow");
div.animate({width:'200px', opacity:'0.8'}, "slow");
div.animate({height:'100px', opacity:'0.4'}, "slow");
div.animate({width:'100px', opacity:'0.8'}, "slow");
div.animate({right:'100px', opacity:'0.8'}, "slow");
div.animate({bottom:'100px', opacity:'0.8'}, "slow");
div.animate({left:'100px', opacity:'0.8'}, "slow");
div.animate({top:'100px', opacity:'0.8'}, "slow", function(){
alert("The paragraph is over"); // ← 這就是回呼函數
});
});
});
</script>
jQuery 的動畫方法簽名是 .animate(properties, duration, easing, complete)。最後那個參數就是 callback:它不是動畫的設定值,而是一個「等這段動畫播完才執行」的函式。
範例中前七個 animate() 都沒有回呼,只有最後一個掛了 function(){ alert(...) },所以提示視窗會等整串動畫走到最後一步才跳出來。如果把 alert 直接寫在 animate 後面(不放在回呼裡),它會在動畫還沒結束時就立刻執行。
"slow"、"normal"、"fast"800
$(document).ready(function(){
$("button").click(function(){
var div = $(".box");
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", function(){
alert("The paragraph is over");
});
});
});
把回呼掛在第四段,alert 就會在第四段結束時跳出,後續動畫仍舊繼續。這說明了回呼只跟「它所在的那一段」綁定。
queue: false。$(this)。把 callback 想成「這件事做完之後要做什麼」,非同步的世界就清楚一半了。