2010-08-13 62 views
0

我正在寻找使用jQuery加载影响CSS的随机边距的Div。以下是我尝试使用的脚本,试图从1-500中随机创建一个数字,并将其作为边距加载。但我不是一个jQuery的专家,我错过了一些东西。Jquery - 用随机边距/位置加载div

非常感谢您的帮助!

<script type="text/javascript"> 

$(function(){ 

$("#randomnumber").load(function() { 

      var numRand = Math.floor(Math.random()*501); 


     $("#randomnumber").css("marginRight",numRand); 


}); 

}); 

</script> 



<div id="page-wrap"> 


     <div id="randomnumber">BIG BOY</div> 

</div> 

回答

0

的问题是没有.load()事件此元素,至少不是一个会不会在负载火,你需要一个.each()这样的:

$("#randomnumber").each(function() { 
    var numRand = Math.floor(Math.random()*501); 
    $(this).css({'margin-left': numRand}); 
});​ 

You can test that here,或因为你正在做一个元素,使其更简单:

var numRand = Math.floor(Math.random()*501); 
$("#randomnumber").css({'margin-left': numRand});​ 

You can test that version here

+0

是的!那会做。非常感谢! – Michael 2010-08-13 18:23:18

0

您的选择器始终需要加引号。

$('#randomnumbers').css() 

此外,它取决于你,但我会建议遵循标准的格式约定。它使你的代码更清晰,并为你希望在未来使用它的其他人提供更清晰的代码。

$(document).ready(function(){ 
    $("#randomnumber").load(function() { 
     var numRand = Math.floor(Math.random()*501); 
     $(this).css({'margin-right': numRand}); 
    }); 
}); 
+0

啊好打电话。谢谢。尽管保证金似乎仍未受到影响? – Michael 2010-08-13 16:34:57

+0

对不起。我错过了一个更正。现在就试试。 – Squirkle 2010-08-13 16:42:18

+0

squirkle,真的很感谢帮助。但似乎仍然存在问题。 你可以在这里看到它作为测试:http://greyyy.com/random/index.html(注:我改变了余量左边,因为我还没有放下任何其他样式)。 – Michael 2010-08-13 17:06:09