随机化容器内元素的位置
randomise position of elements within container
我正试图使用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 ) )
});
})
});
相关文章:
- 从鼠标点(及更多)查询位置元素
- 保持光标位置元素在顶部使用 svg
- 如何在每次页面重新加载时更改渐变背景,同时保持光标位置元素处于活动状态
- 使用JS暂时禁用在位置/元素处滚动
- 相对于另一个元素的位置元素不起作用
- 返回包含随机位置元素的数组
- 如何在 Jquery 中根据屏幕大小移动绝对位置元素
- 如何在html中设置固定位置元素的最大深度
- 无论如何,如果绝对位置元素位于屏幕下方,则使正文滚动条出现
- 绝对位置元素未隐藏在滚动框之外
- 为什么浮动位置 元素缩小时元素不移动
- 固定位置元素…动作
- 当元素处于相对位置元素时,查找元素偏离窗口的jQuery或JavaScript方法
- 绝对位置元素,这样它们的行为就像浮动一样
- jQuery鼠标在菜单和动画位置元素后面
- 捕获绝对位置元素上的单击事件
- 如何设置固定位置元素的高度以达到浏览器窗口的底部
- jQuery绑定位置:元素的绝对位置
- 如何将固定位置元素限制为浏览器窗口的高度
- 如何在不使用JS的情况下使用TOC滚动页面上的固定位置元素