随机渐变背景色

时间:2018-06-15 15:07:35

标签: javascript css background-color linear-gradients

我试图在每个部分上获得随机渐变背景(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>
&#13;
&#13;
&#13;

这是随机的。有时我会得到这样的结果: enter image description here

结果应该是这样的:

enter image description here

2 个答案:

答案 0 :(得分:2)

If you dont try to calculate the remaining % then it seems to work as you expect

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>

答案 1 :(得分:0)

&#13;
&#13;
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);
    }
&#13;
section{
  display:block;
  height:400px;
}
&#13;
<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>
&#13;
&#13;
&#13;

如果您的第一个渐变位置大于50%,则第二个小于第一个。 例如,从红色60%到绿色40%的梯度将是一条直线。 修改你的randomNumber总是<50

显然,当渐变为和相同颜色时,你不会模糊