admin管理员组文章数量:1332865
I have floating RANDOM elements inside DIV, varying LEFT and TOP position inside parent <div class="main"></div>
. How to calculate and set LEFT and TOP positions mathematically in javascript/jQuery so any random element will NOT go beyond boundary defined parent
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()))
});
});
Example : /
Thank you
I have floating RANDOM elements inside DIV, varying LEFT and TOP position inside parent <div class="main"></div>
. How to calculate and set LEFT and TOP positions mathematically in javascript/jQuery so any random element will NOT go beyond boundary defined parent
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()))
});
});
Example : https://jsfiddle/iahmadraza/u5y1zthv/
Thank you
Share asked Mar 17, 2017 at 10:42 AhmadAhmad 1861 gold badge3 silver badges11 bronze badges 2- You have to remove the amount of width/height of the element itself. left : ((Math.random() * ($('.main').width()-$(this).width()))), top : ((Math.random() * ($('.main').height()-$(this).height()))) – Roy Bogado Commented Mar 17, 2017 at 10:49
-
function getRnd(min, max)
withmin = 0
andmax = (main.width - box.width)
– Andreas Commented Mar 17, 2017 at 10:49
1 Answer
Reset to default 5The .box
elements are fixed at 100px
height and width, so to achieve what you need just remove that dimension from the possible random value maximum:
$(this).css({
left: Math.random() * ($('.main').width() - $(this).width()),
top: Math.random() * ($('.main').height() - $(this).height())
});
Updated fiddle
本文标签: javascriptrandom position of elements inside parent divStack Overflow
版权声明:本文标题:javascript - random position of elements inside parent div - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742292399a2448052.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论