随机化容器内元素的位置

randomise position of elements within container

本文关键字:位置 元素 随机化      更新时间:2023-09-26

我正试图使用jquery/javascript在父容器中随机定位多个子元素。这是我目前掌握的代码。任何帮助或想法都会很棒。

如果您能让孩子从不重叠,则可获得奖励积分

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/

试试这个代码。在你的jsfiddle上,我收到了找不到jquery的错误。单击"javascript"按钮,在"frameworks and extensions"下拉列表中添加jQuery。之后,请更新并再次运行。那么它应该会起作用:)。

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