我正在制作这个雪动画,并且我想在某些浏览器上将 FPS 降低一半,因此为此我只需移动 dom 一半的时间。我需要在为每个薄片进行克隆/动画处理后设置一个变量。
我无法在克隆之前设置变量,因为这样“i”变量将是通用的,并且对于每个 flake,它都会增加,需要在 flake 范围内设置。
$flake.clone().appendTo('#snowContainer').css({
left: x,
top: y,
opacity: startOpacity,
width: sizeFlake + '%',
*** I need to initialize the "i" variable here,
or somewhere before the loop "step" starts ***
color: options.flakeColor
}).stop().animate({'border-spacing': 0 },{
step: function(p, fx) {
angle += 0.01;
xadd = (Math.sin(angle) + (sizeFlake/4) * 1.5)/speed;
yadd = (Math.cos(angle) + (sizeFlake/2) / 2)/speed;
x += xadd;
y += yadd;
*** if "i" variable here is not defined it throws an error ***
if(i%2==0)
{
var move = {top: y + "px", left: x + "px"};
$(fx.elem).css(move);
}
i++;
}, duration: 20000, easing:"linear", complete: function (){ $(this).remove(); //console.log("flake deleted");
}
});
最佳答案
您可以使用动画的开始回调
http://api.jquery.com/animate/
start
Type: Function( Promise animation )
A function to call when the animation begins. (version added: 1.8)
或者检查step回调函数的p参数,只拦截动画的第一步。
关于javascript - 如何在 jQuery 克隆/动画之前初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27522394/