2013-10-09 42 views
2

我是一個JS業餘愛好者。我期望隨機設置一堆span元素的寬度和不透明度來創建動畫效果。受約束的隨機數總是總的約束與JavaScript/jquery

目前,寬度設置並重新設置使用setInterval每秒這幾乎是工作的罰款...

$(function() { 
    setInterval(function() { 
    // Variables for background colour 
    var minFloat = 0.3, 
     maxFloat = 0.9, 
     randFloat = Math.floor(Math.random() * (maxFloat - minFloat + 1)) + minFloat; 

    // Set random width 
    $('.footerbars span').css('width', Math.random() * 10 + '%'); 

    // Set random alpha 
    $('.footerbars span').css('background-color', 'rgba(58,130,255,' + randFloat + ')'); 
    }, 1000); 
}); 

我需要的是:

  • 的寬度跨度爲不同的百分比,並且所有這些百分比總是100%。
  • 和背景alpha通道是隨機的每個跨度

任何幫助是真棒!!在此先感謝

回答

1

第一個問題是所有寬度和背景將被設置爲相同的隨機數字只生成一次。你需要這樣的東西:

$('.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) +')'); 
}); 
+0

你的代碼拋出了一些錯誤,這是更好嗎? '$( '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}); ' –

+0

你可以添加最後的代碼作爲參考pls。我不斷收到每個時間間隔的錯誤。然而,酒吧出現,並在不同的寬度和顏色是甜美的 –