random position of divs in javascript

后端 未结 4 932
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 05:48

I\'m trying to make Divs to appear randomly anywhere on a webpage with javascript. So a div appears then disappears, then another div appears somewhere else on the page then

4条回答
  •  盖世英雄少女心
    2020-12-01 06:19

    Let's say you have this HTML:

    test div

    And this CSS:

    #test {
        position:absolute;
        width:100px;
        height:70px;
        background-color:#d2fcd9;
    }
    

    Using jQuery, if you use this script, whenever you click the div, it will position itself randomly in the document:

    $('#test').click(function() {
        var docHeight = $(document).height(),
            docWidth = $(document).width(),
            $div = $('#test'),
            divWidth = $div.width(),
            divHeight = $div.height(),
            heightMax = docHeight - divHeight,
            widthMax = docWidth - divWidth;
    
        $div.css({
            left: Math.floor( Math.random() * widthMax ),
            top: Math.floor( Math.random() * heightMax )
        });
    });
    

    The way this works is...first you calculate the document width and height, then you calculate the div width and height, and then you subtract the div width from the document width and the div height from the document height and consider that the pixel range you're willing to put the div in (so it doesn't overflow out of the document). If you have padding and border on the div, you'll need to account for those values too. Once you've figured out the range, you can easily multiple that by Math.random() and find the random position of your div.

    So once more: first find the dimensions of the container, then find the dimensions of your element, then subtract element dimensions from container dimensions, and THEN use Math.random() on that value.

    The basic idea is encapsulated here:

    http://jsfiddle.net/5mvKE/

提交回复
热议问题