javascript - 慢慢改变背景颜色
问题描述
我的代码可以完美运行,当降低滚动 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";
}
};
解决方案
不要延迟使用 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>
推荐阅读
- python - 在单个数据框中显示所有匹配对 - Python Record Linkage
- asp.net-web-api - 当控制器使用错误的返回类型时,有没有办法发出警告
- java - 为 BigDecimal 设置比例和舍入后舍入必要的异常
- magento2 - 将 Magento1 管理员用户导入 Magento2
- azure-media-services - 如何使用 azure 函数和事件订阅来监听 mediaService 事件
- c# - 通过自定义分隔符将一个大文本文件拆分为较小的文件。每个新文件名都来自较小文件的标题
- angular - 在 macOS mojave 上安装 angular/cli 时出错 - node-pre-gyp
- json - 又抛出了一个异常:HttpException: Connection closed while received data, uri =
- c# - Ninject IntransientScope 不能与 DBContext 一起使用?
- apache-spark-sql - 将 CURRENT_TIMESTAMP() 时间从 UTC 转换为 ET