【发布时间】: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