javascript - 容器内元素的随机位置

标签 javascript jquery css random

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

加分如果你能让 child 永远不会重叠。

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”按钮在“框架和扩展”下拉列表中添加 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 ) )
           });        

    })
});

关于javascript - 容器内元素的随机位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347614/

相关文章:

html - 网站加载时菜单项的外观

javascript - Chrome 扩展 JavaScript 程序无法运行

javascript - 在 Javascript 中从 JSON 文本中提取值?

jquery - 想要使用绑定(bind)和取消绑定(bind)。我希望能够在选择单选按钮后将鼠标悬停在其他行上

jquery - 为什么当我使用 jquery 隐藏它时该元素又显示出来

javascript - 用于选择展开/折叠的 jQuery/javascript 事件?

jquery - slidesjs jquery幻灯片轮播中slides_container上方的空间 - css

html - CSS、HTML 和背景颜色问题。

Javascript 文件在链接时不起作用,但在内部工作?

javascript - jqplot - 想要限制 y 轴刻度