javascript - random position of elements inside parent div - Stack Overflow

I have floating RANDOM elements inside DIV, varying LEFT and TOP position inside parent <div class=&

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) with min = 0 and max = (main.width - box.width) – Andreas Commented Mar 17, 2017 at 10:49
Add a ment  | 

1 Answer 1

Reset to default 5

The .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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742292399a4416444.html

相关推荐

  • javascript - random position of elements inside parent div - Stack Overflow

    I have floating RANDOM elements inside DIV, varying LEFT and TOP position inside parent <div class=&

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信