第一个问题是所有宽度和背景将被设置为相同的随机数字只生成一次。你需要这样的东西:
$('.footerbars span').each(function(i, e) {
$(e).css('width', (Math.random() * 10) + '%')
.css('background-color', 'rgba('58,130,255,' + ((Math.random() * 0.6) + 0.3) +')');
});
这个问题是,宽度可能不会全部加起来100%。为了解决这个问题,我们需要先生成一组随机数,然后对它们进行缩放,使它们合计为100,然后将它们应用于跨度。
var numSpans = $('.footerbars span').length;
var widths = [];
var total = 0;
for(var i = 0; i < numSpans; i++) {
widths[i] = Math.random()+1; // generate a new random width for this span - and make it definitely not zero
total += widths[i]; // and update the total width so far;
}
// Now we know what the total random number is (something between numSpans and 2*numSpans)
// we can scale these so the sum actually is 100
for(var i = 0; i < numSpans; i++)
widths[i] = Math.floor(widths[i] * (100/total));
现在widths[i]
包含.footerbars第i个跨度的%的宽度,因此修改的码的第一个比特的第二行是:
$(e).css('width', widths[i])
全码:
var numSpans = $('.footerbars span').length;
var widths = [];
var total = 0;
for(var i = 0; i < numSpans; i++) {
widths[i] = Math.random()+1; // generate a new random width for this span - and make it definitely not zero
total += widths[i]; // and update the total width so far;
}
// Now we know what the total random number is (something between numSpans and 2*numSpans)
// we can scale these so the sum actually is 100
for(var i = 0; i < numSpans; i++)
widths[i] = Math.floor(widths[i] * (100/total));
$('.footerbars span').each(function(i, e) {
$(e).css('width', widths[i])
.css('background-color', 'rgba('58,130,255,' + ((Math.random() * 0.6) + 0.3) +')');
});
你的代码抛出了一些错误,这是更好吗? '$( 'footerbars跨度 ')。每个(函数(I,E){ \t \t e.css(' 宽度',(的Math.random()* 10)+ '%') \t \t的CSS ('background-color','rgba(58,130,255,'+((Math.random()* 0.6)+ 0.3)+')'); \t}); ' –
你可以添加最后的代码作为参考pls。我不断收到每个时间间隔的错误。然而,酒吧出现,并在不同的宽度和颜色是甜美的 –