2015-12-18 79 views
1

我想隨機使用jquery/javascript在父容器中定位多個子元素。這是我目前的代碼。任何幫助或想法都會很棒。容器內元素隨機位置

積分如果你可以讓孩子永遠不會重疊。

HTML

<div class="container"> 
    <div class="population_man"></div> 
    <div class="population_man"></div> 
    <div class="population_man"></div> 
</div> 

CSS

.container{ 
    width:200px; 
    height:200px; 
    border:1px solid grey; 
    position:relative; 
} 

.population_man{ 
    position:absolute; 
    width:5px; 
    height:10px; 
    background-image:url('http://www.perthurbanist.com/wp-content/uploads/2015/12/Untitled-2.png'); 
} 

JQUERY

$(document).ready(function() { 
$('.population_man').each(function(){ 
    $holder = $(this).parent(); 
    $divWidth = $holder.width(); 
    $divHeight = $holder.height(); 

     $(this).css({ 
      left: Math.floor(Math.random() * $divWidth), 
      top: Math.floor(Math.random() * $divHeight) 
     });   

}) 
}); 

的jsfiddle:https://jsfiddle.net/zL97snxL/21/

回答

1

試試這個代碼。並在你的jsfiddle,我得到的錯誤,無法找到jquery。點擊「javascript」按鈕,在「框架和擴展名」下拉列表中添加jQuery。之後,更新並再次運行。它應該工作:)。

$(document).ready(function() { 
    $('.population_man').each(function() { 

     $holder = $(this).parent(); 
     $divWidth = $holder.width(); 
     $divHeight = $holder.height(); 

      $(this).css({ 
       'left': Math.floor(Math.random() * Number($divWidth)), 
       'top' : Math.floor(Math.random() * Number($divHeight)) 
      });   

    }) 
}); 
+0

工作就像一個魅力,謝謝。 –

+0

我的榮幸。快樂的編碼! –