我正在尝试使用jquery .each函数更改5 div的left / top值。目前,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>
&#13;
答案 0 :(得分: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 ));
});
});
&#13;
.randomSpawn {
position: fixed;
background-color: black;
display: block;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
&#13;
<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>
&#13;