Callback 函數在當前動畫 100% 完成之後執行。
jQuery 動畫的問題
許多 jQuery 函數涉及動畫。這些函數也許會將 speed 或 duration 作爲可選參數。
例子:$("p").hide("slow")
speed 或 duration 參數可以設置許多不同的值,比如 "slow", "fast", "normal" 或毫秒。
實例
$("button").click(function(){
$("p").hide(1000);
});
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").hide(1000); }); }); </script> </head> <body> <button type="button">隱藏</button> <p>This is a paragraph with little content.</p> <p>This is another small paragraph.</p> </body> </html>
由於 JavaScript 語句(指令)是逐一執行的 - 按照次序,動畫之後的語句可能會產生錯誤或頁面衝突,因爲動畫還沒有完成。
爲了避免這個情況,您可以以參數的形式添加 Callback 函數。
jQuery Callback 函數
當動畫 100% 完成後,即調用 Callback 函數。
典型的語法:
$(selector).hide(speed,callback)
callback 參數是一個在 hide 操作完成後被執行的函數。
錯誤(沒有 callback)
$("p").hide(1000);
alert("The paragraph is now hidden");
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").hide(2000); alert("The paragraph is now hidden"); }); }); </script> </head> <body> <button type="button">Hide</button> <p>This is a paragraph with little content.</p> </body> </html>親自試一試
正確(有 callback)
$("p").hide(1000,function(){
alert("The paragraph is now hidden");
});
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").hide(1000,function(){ alert("The paragraph is now hidden"); }); }); }); </script> </head> <body> <button type="button">Hide</button> <p>This is a paragraph with little content.</p> </body> </html>
結論:如果您希望在一個涉及動畫的函數之後來執行語句,請使用 callback 函數。