一些div的起始位置和随机移动

时间:2015-10-28 15:47:53

标签: javascript random

我想制作类似于this动作的内容,但让div从随机位置而不是左上角开始。



$(document).ready(function () {
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv();
});

function newDiv() {
    var $div = $("<div class='a'>");
    $(".animatedDivs").append($div);
    animateDiv();



    function animateDiv() {
        var newq = makeNewPosition();
        var oldq = $div.offset();
        var speed = calcSpeed([oldq.top, oldq.left], newq);

        $div.animate({
            top: newq[0],
            left: newq[1]
        }, speed, 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 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 = .4;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
&#13;
div.a {
    width: 50px;
    height:50px;
    background-color:red;
    position:fixed;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="animatedDivs"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

我为你更新了jsfiddle here

只是添加以下两行:

var newq = makeNewPosition();
var $div = $("<div class='a'>").css({top: newq[0], left: newq[1]});

$(document).ready(function () {
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv();
    newDiv();
});

function newDiv() {
    var newq = makeNewPosition();
    var $div = $("<div class='a'>").css({top: newq[0], left: newq[1]});
    $(".animatedDivs").append($div);
    animateDiv();



    function animateDiv() {
        var newq = makeNewPosition();
        var oldq = $div.offset();
        var speed = calcSpeed([oldq.top, oldq.left], newq);

        $div.animate({
            top: newq[0],
            left: newq[1]
        }, speed, 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 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 = .4;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div.a {
    width: 50px;
    height:50px;
    background-color:red;
    position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="animatedDivs"></div>