简体   繁体   中英

randomise position of elements within container

I am trying to randomly position multiple child elements within a parent container using jquery/javascript. This is the code that I have at the moment. Any help or ideas would be great.

Bonus points if you can make the child never overlap.

HTML

<div class="container">
    <div class="population_man"></div>
    <div class="population_man"></div>
    <div class="population_man"></div>
</div>

CSS

.container{
    width:200px;
    height:200px;
    border:1px solid grey;
    position:relative;
}

.population_man{
    position:absolute;
    width:5px;
    height:10px;
    background-image:url('http://www.perthurbanist.com/wp-content/uploads/2015/12/Untitled-2.png');
}

JQUERY

$( document ).ready(function() {
$('.population_man').each(function(){
    $holder = $(this).parent();
    $divWidth = $holder.width();
    $divHeight = $holder.height();

       $(this).css({
            left: Math.floor(Math.random() * $divWidth),
            top: Math.floor(Math.random() * $divHeight)
       });        

})
});

jsfiddle: https://jsfiddle.net/zL97snxL/21/

Try this code. And on your jsfiddle, I am getting errors that jquery cannot be found. Click the "javascript" button add jQuery in the "frameworks and extensions" dropdown. After that, update and run again. It should work then :).

$( document ).ready(function() {
    $( '.population_man' ).each(function() {

        $holder    = $(this).parent();
        $divWidth  = $holder.width();
        $divHeight = $holder.height();

           $(this).css({
                'left': Math.floor( Math.random() * Number( $divWidth ) ),
                'top' : Math.floor( Math.random() * Number( $divHeight ) )
           });        

    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM