我使用jquery代码有以下javascript:
function MakeAnimation(anim_times)
{
for (k=1; k<=anim_times; k++)
{
if ( $("#one").position().top >= 250 ) {
$("#one").animate({ top: '50px' }, 200, function() {});
} else {
$("#one").animate({ top: '+=50' }, 200, function() {});
}
}
}
和html正文:
<button onclick="MakeAnimation(1);">step 1</button>
<button onclick="MakeAnimation(20);">step 20</button>
<div id="one" style="background-color:red; width:100px; height:100px; position:absolute; top:50px;"></div>
两个按钮调用相同的函数,但是当函数调用20次for for循环时...第5行[if($(“#one”)。position()。top&gt; = 250){]不起作用
有什么建议吗?
感谢
答案 0 :(得分:1)
似乎按预期工作。我为此创建了fiddle。
抱歉,我的坏!要回答AkisC的问题,for
循环是同步的,但animations
是异步的(参考Wait for a jQueryanimation to complete within for loop)。
因此,对于第二个按钮,我们总是在每次迭代时得到'50'作为最高值,并且永远不会执行if ( $("#one").position().top >= 250 ) {
。
我用新方法修改了我的小提琴:http://jsfiddle.net/kayen/3SSeu/
答案 1 :(得分:1)
您需要做的就是将n
调用MakeAnimation
倍,无循环,然后......
您只需使用步骤功能来检索顶部位置属性值。
不要害怕,它在animation
方法中默认可用:
function MakeAnimation(n){
n=n+1; // I used n=n+1 cause you already start from 50px top...
$('#one').animate({ top: 50*n },{
step: function(now) { // the step function!
if(now>=250){
$(this).stop().animate({top: 50 }, 200);
}
},
easing: 'linear', // the default easing in animations is 'swing'
duration: 200*n
});
}