我在 DIV 中有 float 的 RANDOM 元素,在父元素中改变 LEFT 和 TOP 位置 <div class="main"></div>
.如何在 javascript/jQuery 中以数学方式计算和设置 LEFT 和 TOP 位置,以便任何随机元素都不会超出边界定义的父级
HTML:
<div class="main"></div>
Javascript:
for (var i = 0; i < 5; i++) {
$('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
$(this).css({
left : ((Math.random() * $('.main').width())),
top : ((Math.random() * $('.main').height()))
});
});
示例:https://jsfiddle.net/iahmadraza/u5y1zthv/
谢谢
最佳答案
.box
元素的高度和宽度固定为 100px
,因此要实现您需要的效果,只需从可能的随机值最大值中删除该尺寸即可:
$(this).css({
left: Math.random() * ($('.main').width() - $(this).width()),
top: Math.random() * ($('.main').height() - $(this).height())
});
关于javascript - 元素在父 div 中的随机位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855374/