Javascript 使用 CSS3 过渡来动画样式更改



我有一个div,它有一个背景渐变,其值是使用javascript动态设置的。有时,我需要更改渐变值(可以是颜色或颜色停止位置(。我想在不使用javascript的情况下对这些更改进行动画处理(不要误会我的意思,我使用javascript设置了渐变值,但我想使用CSS3对此进行动画处理(。我尝试像使用 CSS 一样设置transition属性。这是MWE:

function getPercent() {
  return Math.random() * 100;
}
setInterval(() => {
  const per = getPercent();
  document.getElementById('foo').style.background =
    `linear-gradient(to right, #aebcbf 0%,#aebcbf ${per}%,#0a0e0a ${per}%,#0a0e0a 100%`
}, 1000)
.container {
  transition: all 1s ease;
  background: linear-gradient(to right, #aebcbf 0%,#6e7774 50%,#0a0e0a 51%,#0a0809 100%);
  width: 150px;
  height: 10px;
}
<div class="container" id="foo"></div>

希望这有用

background: linear-gradient(269deg, #ffffff, #ff0000);
background-size: 400% 400%;
-webkit-animation: AnimationName 23s ease infinite;
-moz-animation: AnimationName 23s ease infinite;
-o-animation: AnimationName 23s ease infinite;
animation: AnimationName 23s ease infinite;
@-webkit-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@-o-keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
@keyframes AnimationName {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}
  • 参考: https://www.gradient-animator.com/

有关 CSS 过渡的更多信息,请查看此内容

  • https://css-tricks.com/almanac/properties/t/transition/

不幸的是,background-image不是可动画的(有关背景图像的更多信息(。因此,对 CSS 渐变进行动画处理是一个问题。

要使用纯 CSS 解决此问题,您可以创建一个包含新渐变的:beforeopacity: 0,并在要显示新渐变时将其更改为opacity: 1

最终我们可以执行以下操作:

.container{
  width: 150px;
  height: 10px;
  background: linear-gradient(to right, #aebcbf 0%, #6e7774 50%, #0a0e0a 51%, #0a0809 100%);
  position: relative;
  z-index: 100;
}
.container:before{
  background: linear-gradient(to right, #aebcbf 0%, #6e7774 10%, #0a0e0a 51%, #0a0809 100%);
  content: '';    
  display: block;
  height: 100%;
  position: absolute;
  top: 0; 
  left: 0;
  opacity: 0;
  width: 100%;
  z-index: -100;
  transition: opacity 0.45s;
}
.container:hover:before {
  opacity: 1;
}
<div class="container" id="foo"></div>

编辑:

如果要使渐变动态化,请使用一个变量来跟踪您上次更改的元素,例如:

var swapElement = 0;
function getPercent() {
  return Math.random() * 100;
}
setInterval(() => {
  const per = getPercent();
  if(swapElement == 0){
     //change gradient of :before
     //set opacity to 1
     swapElement = 1;
  } else {
     document.getElementById('foo').style.background =
    `linear-gradient(to right, #aebcbf 0%,#aebcbf ${per}%,#0a0e0a ${per}%,#0a0e0a 100%`
}, 1000);
     //set opacity :before to 0
     swapElement = 0;
  }

最新更新