Javascript逐渐改变饱和度

Javascript gradually change the saturation

我有一些代码,当按下c键时,饱和度会增加,当抬起c键时,它会恢复正常。我想知道我怎样才能做到这一点,而不是立即改变饱和度水平,饱和度会在半秒内逐渐改变,当键 c 被抬起时,饱和度会在半秒内逐渐降低回到正常的饱和度。如何才能做到这一点? 当前代码:

document.addEventListener("keydown", e => {
  if (e.code === "KeyC") {
document.body.style.filter = "saturate(1.7)";

    
    
    
    }
}, false)

document.addEventListener("keyup", e => {
  if (e.code === "KeyC") {
  document.body.style.filter = "";

  
  }
}, false)

我会使用 CSS 转换来实现渐变。 然后,您可以在元素上执行 .classList.add('saturated').classList.remove('saturated'),而不是使用 javascript 设置饱和值。我用 div:

做了一个例子
#myDiv{
  width:200px;
  height:200px;
  background-color: lightblue;
  filter: saturate(1);
  transition: filter 1s ease;
}

#myDiv.saturated {
  filter: saturate(4);
}

这里有一个关于 JSFiddle 的工作示例:https://jsfiddle.net/martinnester/07fsL2ge/20/