首页 > 解决方案 > 慢慢改变背景颜色

问题描述

我的代码可以完美运行,当降低滚动 x 像素时,我的 manu 的背景会更改为所选颜色。但我不知道如何让那种颜色不是一下子改变,而是慢慢地改变。

window.onscroll = function() {
  var fondo = document.getElementById("fondo")
  if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
    fondo.style.backgroundColor = "rgba(0, 0, 0, 0.8)";
  } else {
    fondo.style.backgroundColor = "transparent";
  }
};

标签: javascript

解决方案


不要延迟使用 JS,而是通过切换类来使用 CSS 过渡。例如:

window.onscroll = scrollFunction;

const fondo = document.getElementById("fondo")
function scrollFunction() {
  fondo.classList.toggle(
    'scrolled', 
    document.body.scrollTop > 200 || document.documentElement.scrollTop > 200
  );
}
#fondo {
  transition: background-color 1s;
  background-color: rgba(180, 0, 0, 0.8);
  height: 700px;
}
#fondo.scrolled {
  background-color: rgba(0, 0, 0, 0.1);
}

.upper {
  height: 230px;
}
<div class="upper">upper</div>
<div id="fondo"></div>


推荐阅读