如何使用JQuery将随机值放入css属性?
我想为已知数量的div生成属性,但我可以找出哪里出错了。我现在尝试的是:如何使用JQuery将随机值放入css属性?,jquery,css,Jquery,Css,我想为已知数量的div生成属性,但我可以找出哪里出错了。我现在尝试的是: $(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(
$(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);
}
});
$(文档).ready(函数(){
对于(var i=1;i,您的代码中有一些错误
$(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);
}
});
$(文档).ready(函数(){
对于(var i=1;i您忘记了css对象中最后一个元素末尾的'
var cssObj =
{
'bottom' : randBottom + 'px',
'height' : randHeight + 'px',
'widht' : randWidth + 'px'
};
代码存在一些问题:
- 使用
width
方法获取元素的大小,使用css([“width”])
不会将宽度作为数字提供给您,而是提供一个名为width
的属性的对象,该属性是一个具有宽度和单位的字符串,例如{width:'420px'}
- 您忘了包含
左侧的样式
- 指定
top
和left
而不是bottom
和left
(您可能需要更改其计算。)
- 您将
'width'
拼错为'widt'
- 在与随机数相乘以计算左位置之前,可能需要减去元素的宽度,否则会得到负值
这将至少将元素放置在某个位置:
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);
}
for(var i=1;iWorks for me: