【问题标题】:Web Animation, how to animate the background rgba colorWeb Animation,如何为背景 rgba 颜色设置动画
【发布时间】:2019-09-02 16:00:28
【问题描述】:

我想在 rgba 中为模态的背景颜色设置动画,使其淡入。我不能将不透明度用作模态内的 div,我不想透明。我不能使用 Jquery,但我正在使用 React。

我没有得到以下错误提示不起作用

const modal = document.getElementById('modal');
modal.animate(
[
  {backgroundColor: 'rgba(255, 0, 0, 0)'}, 
  {backgroundColor: 'rgba(255, 0, 0, 0.8)'}
], 
  {duration: 200, easing: 'ease-in-out', fill: 'forwards'}
);

【问题讨论】:

  • 这段代码对我有用。可以分享MCVE吗?
  • 在探索了下面的解决方案后,我发现它确实有效,我只是看不到它,因为我将不透明度设置为 0

标签: javascript css web-animations


【解决方案1】:

使用 setInterval 函数在 javascript 中改变颜色。

var change=0;
var colorEvent= setInterval("changeColor();", 50);
function changeColor(){
  if(change<100){           
      document.getElementById("modal").style.backgroundColor="rgb(255,0,"+change+")";
  }
  else 
    clearInterval(colorEvent);
  change+=1;
  console.log(change);
}
#modal{
    height:50px;
    background-color:rgb(255,0,0);
}
&lt;div id="modal"&gt;&lt;/div&gt;

或改变不透明度

var change=0.0;
if(change<0.8){
  setInterval(function(){
      document.getElementById("modal").style.backgroundColor="rgb(255,0,0,"+change+")";
      change+=0.01;
  }, 10);
}
#modal{
    height:50px;
    background-color:rgb(255,0,0,0);
}
&lt;div id="modal"&gt;&lt;/div&gt;

【讨论】:

  • 天才解决方案,我喜欢它,不敢相信我没有想到它。我不得不将 rgb 更改为 rgba 以更改不透明度,但是是的!
  • 我看到setinterval一直没有停止运行,如何停止?
  • @Bill,我已经更新了第一个 sn-p。再检查一遍。
猜你喜欢
  • 2022-12-23
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 2016-01-02
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多