【问题标题】:for loop animate element - checking top position on loopfor 循环动画元素 - 检查循环的顶部位置
【发布时间】:2012-09-24 03:27:05
【问题描述】:

我有以下使用 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 循环...第 5 行 [ if ( $("#one").position().top >= 250 ) { ] 确实不工作

有什么建议吗?

谢谢

【问题讨论】:

    标签: jquery for-loop jquery-animate position


    【解决方案1】:

    似乎按预期工作。我为此创建了一个fiddle

    对不起,我的错!要回答 AkisC 的问题,for 循环是同步的,但 animations 是异步的(参考 Wait for a jQueryanimation to complete within for loop)。 因此,对于第二个按钮,我们总是在每次迭代中将“50”作为最高值,并且永远不会执行 if ( $("#one").position().top &gt;= 250 ) {

    我用新方法修改了我的小提琴:http://jsfiddle.net/kayen/3SSeu/

    【讨论】:

    • 动画有效,但正如 AkisC 所述,循环期间不考虑第 5 行“if ( $("#one").position().top >= 250 )”
    • 是的!我不知道动画是异步的。感谢您的回答并感谢您的小提琴:)
    【解决方案2】:

    jsBin demo

    您需要做的就是将调用的n 乘以MakeAnimation没有循环,然后...

    您只需要使用 step 函数来检索顶部位置属性值。 别害怕,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
        }); 
    } 
    

    来自文档:http://api.jquery.com/animate/#step

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2016-01-26
      • 2014-05-10
      • 2015-03-21
      • 1970-01-01
      相关资源
      最近更新 更多