随机渐变背景色

Random gradient background color

我正在尝试在每个部分上获得随机渐变背景(在 4 种颜色之间)。 这是我的代码:

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>

太随意了。有时我得到这样的结果:

当结果应该是这样的:

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,40);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)]+" "+(100-firstGradient)+"%)"
        );
        "background", "linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%)" 
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>

如果你的第一个渐变位置大于50%,第二个比第一个小。 例如,从红色 60% 到绿色 40% 的渐变将是一条直线。 将您的随机数固定为始终 <50

很明显,当从和到的渐变颜色相同时,您不会模糊

如果您不尝试计算剩余的 % 那么它似乎可以按您的预期工作

let colors = ["#ffd0d2","#fffdd0","#d0fffd","#d0d2ff"];
    $(".main").children('section').each(function(){   
        let firstGradient = randomNumber(10,90);
        $(this).css(
            "background", "linear-gradient(141deg, "+colors[randomNumber(0,4)]+" "+firstGradient+"%, "+colors[randomNumber(0,4)] + ")"
        );
    });
    function randomNumber(min,max){
        return Math.floor((Math.random() * max) + min);
    }
section{
  display:block;
  height:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <section></section>
  <section></section>
  <section></section>
</div>