我希望使用 jQuery 加载具有影响 css 的随机边距的 Divs。下面是我尝试使用的脚本,尝试创建一个 1-500 之间的随机数字,并将其加载为边距。但我不是 jQuery 奇才,我错过了一些东西。
非常感谢您的帮助!
<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>
最佳答案
问题是没有 .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});
关于Jquery - 加载具有随机边距/位置的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3478828/