2015-12-15 58 views
1

我正在尝试使用jquery .each函数更改5个div的左/顶值。目前,divs在彼此之上产生,然后不受jquery的影响,这个片段也是如此。我必须改变什么才能让div移动到屏幕上的随机位置。在jQuery中更改多个div位置

$(function() { 
 
    var docHeight = $(window).height(), 
 
    docWidth = $(window).width(), 
 
    $div = $('.randomSpawn'), 
 
    divWidth = $div.width(), 
 
    divHeight = $div.height(), 
 
    heightMax = docHeight - divHeight, 
 
    widthMax = docWidth - divWidth; 
 
    $div.each(function() { 
 
    $(this).css("left", "Math.floor(Math.random() * widthMax)"); 
 
    $(this).css("top", "Math.floor(Math.random() * heightMax)"); 
 
    }); 
 
});
.randomSpawn { 
 
    position: fixed; 
 
    background-color: black; 
 
    display: block; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100px; 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="1" class="randomSpawn"></div> 
 
<div id="2" class="randomSpawn"></div> 
 
<div id="3" class="randomSpawn"></div> 
 
<div id="4" class="randomSpawn"></div> 
 
<div id="5" class="randomSpawn"></div>

+1

你把表达如在CSS方法的字符串。 – Jai

+0

@Jai正确的符号是什么? –

+0

查看答案已发送@CianNoonan。 – Jai

回答

5

你的代码是在一个字符串。你需要它是正常的JS。 )

$(this).css("left", Math.floor(Math.random() * widthMax)); 
    $(this).css("top", Math.floor(Math.random() * heightMax)); 

$(function() { 
 
    var docHeight = $(window).height(), 
 
    docWidth = $(window).width(), 
 
    $div = $('.randomSpawn'), 
 
    divWidth = $div.width(), 
 
    divHeight = $div.height(), 
 
    heightMax = docHeight - divHeight, 
 
    widthMax = docWidth - divWidth; 
 
    $div.each(function() { 
 
    $(this).css("left", Math.floor(Math.random() * widthMax)); 
 
    $(this).css("top", Math.floor(Math.random() * heightMax)); 
 
    }); 
 
});
.randomSpawn { 
 
    position: fixed; 
 
    background-color: black; 
 
    display: block; 
 
    top: 0; 
 
    left: 0; 
 
    width: 100px; 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="1" class="randomSpawn"></div> 
 
<div id="2" class="randomSpawn"></div> 
 
<div id="3" class="randomSpawn"></div> 
 
<div id="4" class="randomSpawn"></div> 
 
<div id="5" class="randomSpawn"></div>