【问题标题】:Random gradient background color随机渐变背景颜色
【发布时间】:2018-11-25 11:00:15
【问题描述】:

我正在尝试在每个部分上获得随机渐变背景(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>

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

什么时候结果应该是这样的:

【问题讨论】:

  • @j08691 好吧,我同意,但在这种情况下并非如此。我的意思是,我可以得到 10% 和 90%,但梯度无论如何都应该起作用。 (在某些情况下,两种颜色之间没有“模糊”
  • 你改变了你的问题,使我的答案有点无效......你不应该在接受答案后改变问题(或者即使在发布后如果它无效)

标签: javascript css background-color linear-gradients


【解决方案1】:

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

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>

【讨论】:

  • 你是对的,但为什么呢?我的意思是为什么你的答案有效? ^^
  • @KaSkuLL 因为随机有时你会得到 50%
【解决方案2】:

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% 的渐变将是一条直线。 将您的 randomNumber 固定为始终

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2012-03-15
    • 2012-07-10
    • 2021-10-31
    • 2021-10-24
    相关资源
    最近更新 更多