2017-03-17 133 views
2

我在DIV內部浮動RANDOM元素,在父親<div class="main"></div>內改變LEFT和TOP位置。如何計算並設定LEFT和數學在javascript TOP位置/ jQuery的,所以任何隨機元素不會超出邊界定義父父div內元素的隨機位置

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/

謝謝

+0

您必須刪除寬/高的量元素本身。 ((Math.random()*($('。main')。width() - $(this).width()))) top :((Math.random()*($( '.main')。height() - $(this).height()))) – Roy

+0

['function getRnd(min,max)'](https://stackoverflow.com/questions/1527803/generating-random-整數在JavaScript中在一個特定的範圍內)與'min = 0'和'max =(main.width - box.width)' – Andreas

回答

4

.box元件固定在100px的高度和寬度,使之達到你所需要的只是從可能的隨機值最大刪除尺寸:

$(this).css({ 
    left: Math.random() * ($('.main').width() - $(this).width()), 
    top: Math.random() * ($('.main').height() - $(this).height()) 
}); 

Updated fiddle