我试图使用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;
}
你的代码是一个字符串.你需要它是正常的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;
}