如何实现Scroll effect:固定裁剪文本,渐变背景滚动?
解决方案:实现固定文本+滚动渐变背景效果
以下提供两种实现方式,分别适配纯CSS需求和灵活的JavaScript方案:
方案一:纯CSS蒙版实现
通过将固定文本作为滚动渐变的蒙版,让渐变仅在文本区域显示,滚动时文本保持固定位置:
<div class="page"> <h1 class="fixed-text">TEST</h1> <div class="scroll-container"> <div class="gradient-content"></div> </div> </div>
body { margin: 0; background-color: #000; overflow-x: hidden; } .page { width: 100vw; height: 100vh; position: relative; } .fixed-text { /* 文本固定在视口中央 */ position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 96px; text-align: center; margin: 0; color: transparent; z-index: 2; } .scroll-container { /* 滚动容器占满视口 */ height: 100vh; width: 100%; overflow-y: scroll; position: absolute; top: 0; left: 0; z-index: 1; } .gradient-content { /* 渐变内容高度超过视口,允许滚动 */ height: 250vh; background: linear-gradient( #000 0%, #66458e 40%, #fff 50%, #66458e 75%, #000 100% ); /* 使用SVG蒙版,仅在文本位置显示渐变 */ -webkit-mask: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 120"><text x="50%" y="50%" dy=".3em" text-anchor="middle" font-size="96" font-family="Arial, sans-serif" fill="white">TEST</text></svg>') center / contain no-repeat; mask: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 120"><text x="50%" y="50%" dy=".3em" text-anchor="middle" font-size="96" font-family="Arial, sans-serif" fill="white">TEST</text></svg>') center / contain no-repeat; }
方案二:JavaScript动态调整背景位置
直接使用background-clip: text,通过监听滚动事件动态调整文本背景的位置,效果更灵活:
<div class="page"> <h1 class="fixed-text">TEST</h1> <div class="scroll-container"> <div class="gradient-content"></div> </div> </div>
body { margin: 0; background-color: #000; overflow-x: hidden; } .page { width: 100vw; height: 100vh; position: relative; } .fixed-text { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 96px; text-align: center; margin: 0; /* 背景裁剪到文本 */ background: linear-gradient( #000 0%, #66458e 40%, #fff 50%, #66458e 75%, #000 100% ); background-clip: text; -webkit-background-clip: text; color: transparent; z-index: 2; } .scroll-container { height: 100vh; width: 100%; overflow-y: scroll; position: absolute; top: 0; left: 0; z-index: 1; } .gradient-content { height: 250vh; }
const scrollContainer = document.querySelector('.scroll-container'); const fixedText = document.querySelector('.fixed-text'); scrollContainer.addEventListener('scroll', () => { // 根据滚动距离调整文本背景的垂直位置 const scrollTop = scrollContainer.scrollTop; fixedText.style.backgroundPositionY = `-${scrollTop}px`; });
方案对比
- 纯CSS方案:无需JavaScript,但蒙版依赖固定SVG文本,若文本内容/样式变更需同步修改SVG代码。
- JavaScript方案:直接使用
background-clip: text,动态适配文本变化,效果更灵活。
内容的提问来源于stack exchange,提问作者Zani
相关产品推荐
相关产品推荐

