请在下面玩小提琴。一个错误应该发生 - 转变它的#34; head"然后朝正确的方向爬行。但是几个错误(从两个向上开始)会破坏它们。 Jquery"每个"返回坐标两次,因此生成两个错误而不是两组坐标。
$(document).ready(function () {
function bug() {
$('.bug').each(function () {
//var bugs = $('.bug').length;
var h = $(window).height() / 2;
var w = $(window).width() / 2;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
//$this = $(this);
//var newCoordinates = makeNewPosition();
var p = $(this).offset();
var OldY = p.top;
var NewY = nh;
var OldX = p.left;
var NewX = nw;
var y = OldY - NewY;
var x = OldX - NewX;
angle = Math.atan2(y, x);
angle *= 180 / Math.PI
angle = Math.ceil(angle);
console.log(p);
$(this).delay(1000).rotate({
animateTo: angle
});
$(this).animate({
top: nh,
left: nw
}, 5000, "linear", function () {
bug();
});
});
};
bug();
});
http://jsfiddle.net/p400uhy2/
http://jsfiddle.net/p400uhy2/4/
答案 0 :(得分:3)
如 @Noah B 所述,问题是每个" bug" 正在为所有"设置循环。错误"
我为每个元素设置bug()
个功能,以便每个"错误" 可以单独设置。
编辑( @Roko C. Buljan 评论)
function bug() {
// ... your code ...
// calculate animation time, so that each of bugs runs same fast in long and short distance:
var top_diff = Math.abs(OldY - nh),
left_diff = Math.abs(OldX - nw),
speed = Math.floor(Math.sqrt((top_diff * top_diff) + (left_diff * left_diff))) * 15;
$(this).animate({
top: nh,
left: nw
}, speed, "linear", function () {
// rerun bug() function only for that single element:
bug.call(this);
});
};
$('.bug').each(bug);
答案 1 :(得分:1)
问题是你有.each()用.each()调用一个函数...所以每个bug都有bug()回调。您只需将bug()
调用移到.each(){}之外。请参阅小提琴:http://jsfiddle.net/p400uhy2/2/