You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据用户页面滚动位置设置网页黑→白渐变背景色?

实现滚动时背景色从黑到白渐变的方案

嘿,作为刚入门JavaScript的新手,能结合已掌握的HTML/CSS来做交互效果超棒!这个滚动背景渐变的需求其实很适合练手,我给你一个清晰的实现方案,每一步都讲明白:

核心原理

我们的目标是把页面滚动的进度转换成颜色值:

  • 页面顶部(滚动进度0%):背景色为纯黑色 rgb(0,0,0)
  • 页面底部(滚动进度100%):背景色为纯白色 rgb(255,255,255)
  • 中间滚动过程:根据滚动进度计算出0-255之间的数值,同步应用到RGB三个通道

完整代码实现

先上可直接运行的完整代码,之后再拆解细节:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滚动背景渐变</title>
    <style>
        /* 让页面有足够高度支持滚动 */
        body {
            margin: 0;
            min-height: 150vh; /* 视口高度的1.5倍,确保能滚动 */
            transition: background-color 0.1s ease; /* 加过渡让颜色变化更平滑 */
        }
    </style>
</head>
<body>
    <script>
        // 监听页面滚动事件
        window.addEventListener('scroll', function() {
            // 1. 计算滚动相关的关键数值
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            const totalScrollableHeight = document.documentElement.scrollHeight - window.innerHeight;
            // 2. 计算滚动进度(限制在0-1之间)
            const scrollProgress = Math.min(Math.max(scrollTop / totalScrollableHeight, 0), 1);
            // 3. 把进度转换成0-255的RGB值
            const colorValue = Math.floor(scrollProgress * 255);
            // 4. 设置背景色
            document.body.style.backgroundColor = `rgb(${colorValue}, ${colorValue}, ${colorValue})`;
        });
    </script>
</body>
</html>

代码细节拆解

  • CSS部分:给body设置min-height: 150vh是为了让页面高度超过视口,这样才能触发滚动;transition属性是让颜色变化更丝滑,不会生硬跳变。
  • JS部分:
    • scrollTop:获取当前已滚动的距离(兼容不同浏览器的写法)
    • totalScrollableHeight:页面总高度减去视口高度,这是用户能滚动的最大距离(滚动到底部时,scrollTop就等于这个值)
    • scrollProgress:用Math.min和Math.max把进度限制在0-1之间,避免滚动超出范围时颜色出错
    • colorValue:把0-1的进度转换成0-255的整数,因为RGB颜色值是0到255的整数
    • 最后把计算出的颜色值应用到body的背景色上

优化小技巧

如果觉得滚动时颜色变化太频繁(scroll事件会触发很多次),可以加个防抖函数来减少计算次数,优化性能:

// 防抖函数:延迟执行代码,避免频繁触发
function debounce(func, delay = 10) {
    let timeoutId;
    return function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, arguments), delay);
    };
}

// 用防抖后的函数监听滚动
window.addEventListener('scroll', debounce(function() {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const totalScrollableHeight = document.documentElement.scrollHeight - window.innerHeight;
    const scrollProgress = Math.min(Math.max(scrollTop / totalScrollableHeight, 0), 1);
    const colorValue = Math.floor(scrollProgress * 255);
    document.body.style.backgroundColor = `rgb(${colorValue}, ${colorValue}, ${colorValue})`;
}));

扩展玩法

如果之后想尝试其他渐变效果,比如从黑到蓝色,只需要修改RGB值就行:

// 黑→蓝:R和G保持0,B从0到255
document.body.style.backgroundColor = `rgb(0, 0, ${colorValue})`;

或者用HSL颜色模式更简单,直接控制亮度从0%到100%:

const brightness = Math.floor(scrollProgress * 100);
document.body.style.backgroundColor = `hsl(0, 0%, ${brightness}%)`;

内容的提问来源于stack exchange,提问作者Harry Day

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:41:19