第一個問題是所有寬度和背景將被設置爲相同的隨機數字只生成一次。你需要這樣的東西:
$('.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。我不斷收到每個時間間隔的錯誤。然而,酒吧出現,並在不同的寬度和顏色是甜美的 –