第一个问题是所有宽度和背景都将设置为相同,因为随机数只生成一次。你需要类似的东西:
$('.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) +')');
});