Callback 函数在当前动画 100% 完成之后执行。
由于 JavaScript 语句(指令)是逐一执行的 - 按照次序,
动画之后的语句可能会产生错误或页面冲突,因为动画还没有完成,
为了避免这个情况,您可以以参数的形式添加 Callback 函数。
jQuery 动画
许多 jQuery 函数涉及动画。这些函数也许会将 speed 或 duration 作为可选参数。
speed 或 duration 参数可以设置许多不同的值,比如 "slow", "fast", "normal" 或毫秒。
<!DOCTYPE html> <html> <head> <script src="../jquery/jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").hide(1000); }); }); </script> </head> <body> <button type="button">隐藏</button> <p>这是一个段落。</p> <p>这是另一个段落。</p> </body> </html>
$(selector).hide(speed,callback)callback 参数是一个在 hide 操作完成后被执行的函数。
<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)
<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 函数。
评论