我正在寻找帮助编写一个jquery来随机地在页面中放置100个元素。完成时应该如下所示:
到目前为止,我有html,我可以显示100个div,而不是随机放置。我在这里缺少什么?
<html>
<head>
<title>jQuery: Placing Random Elements</title>
<meta charset="utf-8">
<style>
div {
position: absolute;
background-color: lightblue;
opacity: .5;
width: 100px;
height: 100px;
box-shadow: 3px 3px 5px gray;
}
</style>
</head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
$(function() {
var width = $(window).width();
var height = $(window).height();
var div = $('#div');
var makeDiv = function(){
var $newdiv;
for (var i = 0; i < 100; i++) {
$newdiv = $('<div id="div"></div>').addClass('div');
$('body').append($newdiv);
}
}; makeDiv();
});
</script>
<body>
</body>
</html>
答案 0 :(得分:1)
您在代码中缺少顶部和左侧定位,它必须是随机的......
以下是一些改进的代码:
小提琴:http://jsfiddle.net/acrashik/B4xF9/2/
<head>
<title>jQuery: Placing Random Elements</title>
<meta charset="utf-8">
<style>
div {
position: absolute;
background-color: lightblue;
opacity: .5;
width: 100px;
height: 100px;
box-shadow: 3px 3px 5px gray;
}
</style>
</head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script>
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$(function() {
var maxLeft = parseInt($(window).width() - 100,10);
var maxTop = parseInt($(window).height() - 100,10);
var html = '';
for (var i = 0; i < 100; i++) {
html += '<div id="div" style="top:'+getRandomInt(0,maxTop)+'px;left:'+getRandomInt(0,maxLeft)+'px" class="div"></div>';
}
$('body').append(html);
});
</script>
<body>
</body>
</html>