2013-10-09 41 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。我不断收到每个时间间隔的错误。然而,酒吧出现,并在不同的宽度和颜色是甜美的 –