我有一個簡單的頁面,使用2個函數來回動畫框:animateLeft和animateRight。當我打電話動畫這種方式,它工作正常:JQuery動畫回調
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);
然而,當我把這種方式:
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft());
功能animateLeft()不會等到動畫完成之前出現它執行。 animateLeft()立即被調用,導致堆棧溢出。有人能幫我理解這兩條線的區別,以及它們爲什麼會有不同的表現。
完整的應用程序如下所示。
<head>
<script src="../JSCommon/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var stop = false;
$(document).keydown(function(event) {
stop = !stop;
if (!stop)
animateRight();
});
function animateRight() {
if(!stop) {
console.log('animateRight');
$("#divTestBox3").animate({ "left" : "200px" }, 1000, animateLeft);
}
}
function animateLeft() {
if(!stop) {
console.log('animateLeft');
$("#divTestBox3").animate({ "left" : "20px" },1000,animateRight);
}
}
});
</script>
</head>
<body>
<div style="height: 40px;">
<div id="divTestBox3" style="height: 20px; width: 20px; left: 20px; background-color: #89BC38; position: absolute;"></div>
</div>
<p>Press any key to start/stop the animation</p>
</body>