我正在尝试使用 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/