约束随机数总是使用javascript / jquery来约束约束

时间:2013-10-09 15:06:54

标签: javascript jquery random width

我是一名JS业余爱好者。我想随机设置一堆span元素的宽度和不透明度来创建动画效果。

目前,每隔一秒使用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 个答案:

答案 0 :(得分: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) +')');
});