2013-01-24 35 views
1

我想生成已知数量的div的属性,但我可以弄清楚我哪里出错了。我曾尝试现在是:如何将随机值放入使用JQuery的css属性中?

$(document).ready(function(){ 
    for(var i=1; i<=7; i++) 
    { 
    var randBottom = Math.ceil(Math.random()*200); 
    var randHeight = Math.ceil(Math.random()*300)+200-randBottom; 
    var randWidth = Math.ceil(Math.random()*50)+20; 
    var oceanWidth= $("#ocean").css(["width"]); 
    var randLeft= Math.ceil(Math.random()*oceanWidth)-randWidth; 
    var cssObj = { 
     'bottom' : randBottom+'px', 
     'height' : randHeight+'px', 
     'widht' : randWidth+'px 
     }; 
    $("#bubble"+i).css(cssObj); 
    } 
}); 

Here是一个完整的工作正在进行样品。

+0

工作对我来说:http://jsfiddle.net/JdkPb/ –

回答

1

有一些问题与代码:

  • 使用width方法来获取元素的大小,使用css(["width"])不给你的宽度为一个数字,它给你一个具有名称为width的属性的对象,它是具有宽度和单位的字符串,例如{ width: '420px' }
  • 您忘记了包含left的样式。
  • 指定topleft而不是bottomleft。 (您可能需要更改计算。)
  • 您拼写错误'width''widht'
  • 您可能需要在乘以随机数以计算左边位置之前减去元素的宽度,否则您将得到负值。

这将至少放置元素的地方:

for(var i=1; i<=7; i++) 
    { 
    var randBottom = Math.ceil(Math.random()*200); 
    var randHeight = Math.ceil(Math.random()*300)+200-randBottom; 
    var randWidth = Math.ceil(Math.random()*50)+20; 
    var oceanWidth= $("#ocean").width(); 
    var randLeft= Math.ceil(Math.random()*(oceanWidth-randWidth)); 
    var cssObj = { 
     'left': randLeft + 'px', 
     'top' : randBottom+'px', 
     'height' : randHeight+'px', 
     'width' : randWidth+'px' 
     }; 
     console.log(cssObj); 
    $("#bubble"+i).css(cssObj); 
    } 
1

代码中存在一些错误。

$(document).ready(function(){ 
    for(var i=1; i<=7; i++) 
    { 
    var randBottom = Math.ceil(Math.random()*200); 
    var randHeight = Math.ceil(Math.random()*300)+200-randBottom; 
    var randWidth = Math.ceil(Math.random()*50)+20; 
    var oceanWidth= $("#ocean").css(["width"]); 
    var randLeft= Math.ceil(Math.random()*oceanWidth)-randWidth; 
    var cssObj = { 
     'bottom' : randBottom+'px', 
     'height' : randHeight+'px', 
     'width' : randWidth+'px' 
     }; 
    $("#bubble"+i).css(cssObj); 
    } 
}); 
1

您忘记'在CSS对象的最后一个元素的末尾。

var cssObj = 
{ 
    'bottom' : randBottom + 'px', 
    'height' : randHeight + 'px', 
    'widht' : randWidth + 'px' 
};