DIV CSS 佈局教程網

搞懂 jQuery 回呼函數 callback:讓一串動畫照順序發生
編輯:JQuery特效代碼     

為什麼連續寫好幾個 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 後面(不放在回呼裡),它會在動畫還沒結束時就立刻執行。

duration 可以寫什麼

  • 預設關鍵字:"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 就會在第四段結束時跳出,後續動畫仍舊繼續。這說明了回呼只跟「它所在的那一段」綁定。

實務上的兩個提醒

  • 同一元素的動畫預設會排隊。jQuery 的 fx queue 讓串寫的 animate 依序播放;若不想排隊,可在選項中設 queue: false。
  • 回呼裡的 this 是 DOM 元素。若要繼續用 jQuery 方法,記得寫成 $(this)。

把 callback 想成「這件事做完之後要做什麼」,非同步的世界就清楚一半了。

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