jQuery 動畫隊列
當在jQuery對象上調用動畫方法時,如果對象正在執(zhí)行某個動畫效果,那么新調用的動畫方法就會被添加到動畫隊列中,jQuery會按順序依次執(zhí)行動畫隊列的每個動畫。
jQuery提供了以下幾種方法來操作動畫隊列。
-
stop([clearQuery],[gotoEnd]):停止當前jQuery對象里每個DOM元素上正在執(zhí)行的動畫。 -
queue([queueName,]callback):將callback動畫數(shù)添加到當前jQuery對象里所有DOM元素的動畫函數(shù)隊列的尾部。 -
queue([queueName,]naeQueue):用newQueue動畫函數(shù)隊列代替當前jQuery對象里所的DOM元素的動畫函數(shù)隊列。 -
dequeue():執(zhí)行動畫函數(shù)隊列頭的第一個動畫函數(shù),并將該動畫函數(shù)移出隊列。 -
clearQueue([queueName]):清空動畫函數(shù)隊列中的所有動畫函數(shù)。
舉個例子:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
.box {
top: 30px;
position: absolute;
width: 200px;
height: 200px;
background-color: red;
}
body {
position: relative;
}
span {
margin-right: 10px;
}
</style>
</head>
<body>
<span>動畫序列剩余</span>
<span class="num">0</span>
<span>部分</span>
<div class="box"></div>
<button class='btn'>點擊開始動畫</buton>
<script>
function runIt(){
//獲取動畫隊列進度
showIt();
//動畫第一部分
$('.box').animate({ left: '100', },1000)
//動畫第二部分
$('.box').animate({ width:'400', },1000)
//動畫第三部分
$('.box').animate({ left: '0'},1000)
//動畫第四部分
$('.box').animate({ width:'200' },1000)
//動畫第五部分
$('.box').slideUp(1000)
//動畫第六部分
$('.box').slideDown(1000,runIt)
}
function showIt(){
var num = $('.box').queue().length;
//獲取動畫隊列剩余長度
$('.num').text(num);
setTimeout(showIt,1000)
//設置循環(huán)更新動畫隊列的進展
}
$('.btn').on('click',runIt)
//當點擊button的時候,開始啟動動畫
</script>
</body>
</html>