Jquery - 加载具有随机边距/位置的 div

标签 jquery css position margin

我希望使用 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});​

You can test that version here .

关于Jquery - 加载具有随机边距/位置的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3478828/

相关文章:

javascript - 多个 YouTube iframe 播放播放此内容

javascript - "Uncaught TypeError: Cannot read property ' 在 angularJS/NodeJS 中使用 strip 支付方法 Stripe.charges.create({}) 时创建 ' of undefined"

xslt - XSLT中的条件位置检查

javascript - 使用java脚本在div中随机定位一个绝对元素

jquery - 通过 gmap3 显示 map 时出错

JavaScript 函数只影响带有类的第一个 div

html - 如何使用 CSS 隐藏 UL 的前 3 个 child

CSS背景重复线性渐变

html - 需要有关 html/css 编码的建议

JavaScript 获取最近单击的字符的页面坐标