Javascript math.round和使用jQuery在页面上随机移动div
我想随机移动页面中的每个div。这段代码有效,但所有div一起移动。我希望每个div以不同的方式移动。我怎样才能做到这一点Javascript math.round和使用jQuery在页面上随机移动div,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我想随机移动页面中的每个div。这段代码有效,但所有div一起移动。我希望每个div以不同的方式移动。我怎样才能做到这一点 $(document).ready(function(){ animateDiv(); }); function makeNewPosition(){ // Get viewport dimensions (remove the dimension of the div) var h = $(window).height() - 50; var
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}
编辑以使其连续
function animateAllDiv () {
$('.a').each(function() {animateDiv($(this));});
}
function animateDiv ($e){
var newq = makeNewPosition();
var oldq = $(this).offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$e.animate({ top: newq[0], left: newq[1] }, speed,function() {animateDiv($e);} );
});
};
此链接可以帮助查看我的所有代码函数randomcolor(){var r=randomNum(255);var g=randomNum(255);var b=randomNum(255);var color='rgb('+r+','+g+','+b+'))';return color;};为random collor编写此代码,但我不知道必须在何处回调此函数我希望我的div collor更改randomlythnx工作,但工作一次我想反复移动,请“d为使其连续,请尝试使用$(this)。animate({top:newq[0],left:newq[1]},speed,function(){animateDiv();});函数randomcolor(){var r=randomNum(255);var g=randomNum(255);var b=randomNum(255);var color='rgb('+r+','+g+','+b+'));返回颜色;};我为random coller编写了此代码,但我不知道必须在何处回调此函数我希望我的div coller随机更改不要以这种方式使用回调,它将在每个div处回调;使用
setInterval
让您的animateDiv每隔xxx毫秒调用一次