【问题标题】:jQuery animate "step" option breaking animation/speed settingsjQuery动画“步骤”选项破坏动画/速度设置
【发布时间】:2014-11-09 15:02:24
【问题描述】:

我正在使用最初在这个问题中找到的代码:how to get a div to randomly move around a page (using jQuery or CSS)

我已经编辑了代码以使用不同数量的 div,而不仅仅是一个。这是我的代码的小提琴与两个移动的 div:http://jsfiddle.net/FireBot/ordkyjmx/。最后,页面上会有 5 到 10 个 div 移动。

function animateOrbs(){
$('.orb').each(function(){
    var newq = makeNewPosition();
    var oldq = $(this).offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $(this).animate({ top: newq[0], left: newq[1] }, speed, function(){
        animateOrbs();
    });
});
}

我需要对所有移动的 div 进行碰撞检测,这样它们就不会重叠,而是停止或相互反弹。根据我的研究,听起来我需要比较所有动画 div 的位置并检查它们是否相同。作为一个起点,我想我会使用 jQuery animate "step" 选项来获取 div 在移动时的位置并打印每个相应 div 中的数字。

function animateOrbs(){
$('.orb').each(function(){
    var newq = makeNewPosition();
    var oldq = $(this).offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $(this).animate(
        {top: newq[0], left: newq[1]},
        {step: function(){
            var pos = $(this).position();
            var posRight = pos.left + $(this).width();
            var posBottom = pos.top + $(this).height();

            var posData ='Top: ' + pos.top.toFixed(0) + '<br />Left: ' + pos.left.toFixed(0) + '<br />Right: ' + posRight.toFixed(0) + '<br />Bottom: ' + posBottom;

            $(this).html('<div>' + posData + '</div>');
        }}, 
        speed, 
        function(){
            animateOrbs();
        }
    );
});
}

使用步骤代码后,动画现在似乎忽略了速度设置并且不再重复。这是带有 step 选项的同一脚本的小提琴:http://jsfiddle.net/FireBot/u6x84ho9/

我希望 div 在屏幕上缓慢移动,就像在我的第一个小提琴中一样,同时在它们移动时仍然打印它们的当前位置。我已经检查并仔细检查了我的代码,据我所知,我的“步骤”实现与此处的示例相匹配:http://api.jquery.com/animate/。感谢您的帮助!

顺便说一句,如果我的碰撞检测方向完全错误,也请告诉我!

【问题讨论】:

    标签: jquery jquery-animate


    【解决方案1】:

    1) 你的小提琴不起作用,因为你为.animate 使用了错误的签名。正如link you gave youself 提供的那样,使用step 需要第二个签名:

    $("selector").animate(properties, options);
    

    两个参数都必须是对象,并且没有更多参数,因此您必须将 step-function、speed、callback-function 和所有其他参数放入 options 对象中,如下所示:

    $(this).animate(
        {top: newq[0], left: newq[1]}, // properties object
        {                              // open options object
            step: function() {/* your stepping code */},
            duration: speed,
            complete : animateOrbs // since animateOrbs is a function there's no wrapping function needed
            // more options, use the names predefined by jQuery!
        }                              // close options object
    ); // close animate
    

    更新FIDDLE here

    2) 关于碰撞检测的一些提示:

    通常,您的碰撞检测方法是正确的。检测其中一个边或角是否在另一个 div 的边界内就足够了(而且确实有足够的数学要做)。因此,您必须能够访问其他 div 的值。您应该考虑将所有数据存储在函数外部的数组或对象中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      相关资源
      最近更新 更多