如何实现滚动条随页面滚动切换渐变颜色?
实现滚动条随页面滚动切换渐变颜色效果
问题描述
当前滚动条采用固定渐变颜色,无论页面滚动到顶部还是底部,渐变效果均无变化,希望实现页面滚动时滚动条渐变颜色动态切换的效果。
当前实现代码如下:
CSS代码
/* width */ ::-webkit-scrollbar { width: 19px; } /* Track */ ::-webkit-scrollbar-track { background: rgba(0,0,0,1); border-color:black; border-radius:20px; } /* Handle */ ::-webkit-scrollbar-thumb { background-image: linear-gradient(to bottom, #ee7752, #e73c7e, #23a6d5, #23d5ab); animation: scroll-gradient 5s ease infinite; background-size: 100% 100%; border-radius:20px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #7333B1; } body { height:100vw; }
HTML代码
<body> <h1 style="height:200px">hello</h1> </body>
解决方案
由于WebKit滚动条的样式无法直接通过CSS响应滚动事件,我们可以通过CSS自定义属性+JavaScript监听滚动的方式实现动态渐变效果:
1. 修改CSS代码,使用自定义属性控制渐变颜色
/* width */ ::-webkit-scrollbar { width: 19px; } /* Track */ ::-webkit-scrollbar-track { background: rgba(0,0,0,1); border-color: black; border-radius: 20px; } /* Handle */ ::-webkit-scrollbar-thumb { /* 使用自定义属性绑定渐变起止色 */ background-image: linear-gradient(to bottom, var(--color-start), var(--color-end)); border-radius: 20px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: #7333B1; } body { height: 100vw; /* 初始化自定义属性 */ --color-start: #ee7752; --color-end: #23d5ab; }
2. 添加JavaScript监听滚动事件,动态更新颜色
// 定义多组渐变颜色对,对应不同滚动阶段 const gradientColorPairs = [ { start: '#ee7752', end: '#e73c7e' }, { start: '#e73c7e', end: '#23a6d5' }, { start: '#23a6d5', end: '#23d5ab' }, { start: '#23d5ab', end: '#ee7752' } ]; function updateScrollbarColors() { const scrollTop = window.scrollY; const totalScrollHeight = document.documentElement.scrollHeight - window.innerHeight; // 计算滚动进度比例(0表示顶部,1表示底部) const scrollProgress = totalScrollHeight > 0 ? scrollTop / totalScrollHeight : 0; // 根据进度匹配对应的颜色组 const pairIndex = Math.floor(scrollProgress * gradientColorPairs.length); const targetColors = gradientColorPairs[pairIndex % gradientColorPairs.length]; // 更新body上的自定义属性 document.body.style.setProperty('--color-start', targetColors.start); document.body.style.setProperty('--color-end', targetColors.end); } // 绑定滚动事件 window.addEventListener('scroll', updateScrollbarColors); // 页面加载时初始化颜色 updateScrollbarColors();
效果说明
- 页面滚动时,JS会实时计算滚动进度,根据进度切换滚动条thumb的渐变颜色组
- 若需要更平滑的颜色过渡,可以扩展代码实现RGB颜色插值(将十六进制颜色转为RGB值,根据滚动进度计算中间色)
内容的提问来源于stack exchange,提问作者JDIPro
相关产品推荐
相关产品推荐

