最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论