У меня есть простая страница, которая анимирует блок вперед и назад, используя 2 функции: animateLeft и animateRight.Когда я вызываю анимацию таким образом, она работает нормально:
$("#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>