繁体   English   中英

CSS 背景渐变动态 animation

[英]CSS Background gradient dynamic animation

我有一个背景渐变 animation 的页面。

<div class="bg-gradient">

</div>

.bg-gradient {
    width: 400px;
    height: 240px;
    background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
    background-size: 400% 400%;
    animation: gradient 15s ease infinite;
}

@keyframes gradient {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

我想在页面加载时更改 colors。 但这是行不通的。

$(document).ready(function() {
  SetBackgroundColors();
});

function SetBackgroundColors() {
  $('.bg-gradient').css('background', 'linear-gradient(-45deg,' + GetRandomColor() + ',' + GetRandomColor() + ',' + GetRandomColor() + ',' + GetRandomColor() + ')');
}

function GetRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

colors 确实发生了变化,但未应用 animation。 这是小提琴

更新background值后, background-size也会重置为正常值(实际上会重置任何短手值),因此您还需要重新重置/指定其值或仅重置background-image ;)

 $(document).ready(function() { SetBackgroundColors(); }); function SetBackgroundColors() { $('.bg-gradient').css('background', 'linear-gradient(-45deg,' + GetRandomColor() + ',' + GetRandomColor() + ',' + GetRandomColor() + ',' + GetRandomColor() + ')').css('background-size', '400% 400%'); } function GetRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }
 .bg-gradient { width: 400px; height: 240px; background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); background-size: 400% 400%; animation: gradient 15s ease infinite; } @keyframes gradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="bg-gradient"> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM