我注意到一些我无法解释的东西。我制作了这个增加或缩小蓝色框的JavaScript代码。脚本在这里:Javascript setInterval question
var animated = {
timer : null,
el : document.getElementById("divNavyBox"),
startGrowAnimation : function() {
this.stopAnimation();
this.timer = setInterval(
animated.doAnimation(5), 10);
},
startShrinkAnimation : function() {
this.stopAnimation();
this.timer = setInterval(function() {
animated.doAnimation(-5);
}, 10);
},
stopAnimation : function() {
clearInterval(this.timer);
},
doAnimation : function(amount) {
var size = this.el.offsetWidth;
if ((amount > 0 && size < 200) || (amount < 0 && size > 0)) {
this.el.style.width = size + amount + "px";
this.el.style.height = size + amount + "px";
} else {
this.stopAnimation();
}
}
};
当调用动画类的startGrowAnimation方法时,盒子会直观地增长,直到它达到一定的宽度和高度。然后停止。 startGrowAnimation代码如下所示:
startGrowAnimation : function() {
this.timer = setInterval(function() {
animated.doAnimation(5);
}, 10);
}
此代码运行得很好。但是,我不明白为什么有必要在参数中放置一个匿名函数,而不仅仅是普通的调用函数。所以,我取代了代码上面代码如下:
startGrowAnimation : function() {
this.stopAnimation();
this.timer = setInterval(animated.doAnimation(5), 10);
},
当我使用此代码,出于某种原因,盒子大小只有通过每次startGrowAnimation方法被调用五个像素增加。
那么,为什么在这种情况下需要在一个匿名函数调用中包含startGrowAnimation方法呢?
+1 - 伟大的,发人深省的问题! – jmort253 2011-06-09 06:04:03