0

好的,所以我有这段代码,其中每 2 秒将正文中的 div 数量加倍附加到正文中。但是我希望这个 div 位于视口内的随机位置,我该如何实现呢?每次其余的只是堆叠并离开视口时,我的代码中只有第一个 div 实际上出现在随机位置,这里是 jsfiddle:

http://jsfiddle.net/hy4fq/2/

<!doctype html>
<html>
<head>
<title>jQuery Project: An exploding game</title>
<meta charset="utf-8">
<style>
body, html {
width: 960;
height: 500%;
}
div.box {
position: relative;
width: 100px;
height: 100px;
background-color: orange;
}
div.exploding {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"> </script>
<script>
$(document).ready(function(){
$("body").append("<div class='box'></div>");
    // add new div *2
    $("div.box").each(function() {
             var numRand = Math.floor(Math.random()*501);
            $(this).css({'margin-left': numRand});
                setInterval(function()                {$(".box").clone().appendTo("body");}, 3000);

})  

    });





</script>
</head>
<body>
</body>
</html>
4

2 回答 2

1

这是导致我得到这个答案的链接:javascript中div的随机位置

首先,您需要在每次调用该函数时更新随机值。在您的示例中,它位于每个函数中,如果您查看开发人员工具,您会发现它仅在第一次设置该值。

其次,如果您希望将 div 放置在视口内,则在出现的 div 上使用 position:absolute 比 position:relative 更好(在这种情况下),因为如果您使用 position relative ,则每次 div 时身体的高度都会增加被添加。

function makeDiv() {
        var numRand = Math.floor(Math.random() * 501);
        var divsize = 100;
        var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
        var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
        $newdiv = $("<div class='exploding'></div>").css({
            'left': posx + 'px',
                'top': posy + 'px'
        });
        $newdiv.appendTo('body').delay(2000).fadeIn(100, function () {
            //$(this).remove();
            makeDiv();
        });
    }

这是它的工作演示:http: //jsfiddle.net/hy4fq/3/

于 2013-08-07T19:21:47.910 回答
0

您需要不断重新定义 numbRand,它只定义一次,然后用于每个 div。也许创建另一个函数并只返回 numbRand,然后每次调用它,这样它每次都会拉一个随机数。

于 2013-08-07T18:35:40.467 回答