为每个div创建随机顶部,右侧

时间:2013-12-12 15:42:51

标签: javascript jquery

我想为每个div创建随机顶部,右边

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.cube {
    width:50px;
    height:50px;
    background-color:red;
    border-radius:25px;
    position:absolute;
}
</style>
<script src="jquery.js"></script>
<script>
$(function () {
    var Wh = window.innerHeight;
    var number = 1 + Math.floor(Math.random() * Wh);
    $('.cube').each(function() {
          $(this).css({"right":number+"px","top":number+"px"});
    });
});
</script>

</head>

<body>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
</body>
</html>

我不知道为什么每个功能都不能在这里工作! 我看到只有一个div改变了,我该如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

关闭<div>并将ID更改为类:

<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>
<div class="cube"></div>

现在,我认为您希望对每个多维数据集应用不同的位置,因此请更改您的代码:

$(function () {       
    var Wh = window.innerHeight;
    $('.cube').each(function() {
         var number = 1 + Math.floor(Math.random() * Wh);
        $(this).css({"right":number+"px","top":number+"px"});
    });
});

$(this)部分很重要,因为它将定位应用于单个DOM元素,而不是所有具有.cube类的元素。

更新

同时将随机数生成器移动到each函数中,以便每次都生成一个新数字。

答案 1 :(得分:0)

Booo,你不能这样做:<div id="cube"><div id="cube"><div id="cube">

Id必须始终是唯一的。你需要使用课程。像这样:<div class="cube">

在JavaScript中引用$('.cube')

也关闭那些div人。

您的JavaScript应如下所示:

<script>
$(function () {
    var wh = window.innerHeight;


    $('.cube').each(function() {
        var number = 1 + Math.floor(Math.random() * wh);
        //$(this) refers to the current object in the 'each' iteration
        $(this).css({"right":number+"px","top":number+"px"});
    });
});
</script>