约束随机数总是用javascript/jquery对约束求和

Constrained random numbers always total the constraint with javascript/jquery

本文关键字:约束 jquery 求和 随机数 javascript      更新时间:2023-09-26

我是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 通道是随机

任何帮助都很棒!!提前致谢

第一个问题是所有宽度和背景都将设置为相同,因为随机数只生成一次。你需要这样的东西:

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