clearQueue() 的作用是把指定元素上「還沒轮到執行」的佇列項目全部丟掉。當動畫堆得太多、想緊急煞車時,它比一個個 stop() 更乾脆。
不帶參數時,clearQueue() 預設清的是動畫佇列(fx),行為上和 stop(true) 有點像。但兩者的能力範圍不同:stop() 只能處理動畫佇列,而 clearQueue() 可以搭配自訂佇列名稱,清掉任何以 queue() 建立的佇列。
$(selector).clearQueue(queueName)
參數 queueName 是可選的,用來指定要清空的佇列名稱,預設值為 "fx",也就是動畫佇列。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>clearQueue() 示範</title>
<style type="text/css">
#father
{
background:#060;
width:300px;
height:300px;
}
#box
{
background:red;
height:50px;
width:50px;
position:relative;
}
</style>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#start").click(function(){
$("#box").animate({height:200},"slow");
$("#box").animate({width:200},"slow");
$("#box").animate({height:50},"slow");
$("#box").animate({width:50},"slow");
});
$("#clear").click(function(){
$("#box").clearQueue();
});
});
</script>
</head>
<body>
<p>
<button id="start">開始執行動畫</button>
<button id="clear">清除佇列</button>
</p>
<div id="father">
<div id="box"></div>
</div>
</body>
</html>
點擊「開始執行動畫」後,四段動畫會依序排入佇列。此時再按「清除佇列」,正在跑的那一段不受影響(它已經在執行中了),但後面還排著等待的動畫會被整批丟掉,方塊就停在當時的大小不再變動。
若你希望連正在執行中的動畫也一併停止,就該搭配 .stop(true);若只想清空等待中的部分,clearQueue() 就是最合適的工具。