0

我想随机移动页面中的每个 div。此代码有效,但所有 div 一起移动。我希望每个 div 以不同的方式移动。我怎样才能做到这一点?

$(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;

}

jsfiddle

4

1 回答 1

2

编辑以使其连续

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);} );

   });

 };
于 2013-11-07T06:17:18.717 回答