如何实现滚动时背景图移动的Parallax(视差)3D视觉效果?
实现滚动视差头部效果的解决方案
核心思路
- 重构HTML结构,将前景图与背景图放入同一容器,保证两者宽度匹配
- 通过JavaScript监听页面滚动,计算背景图的垂直偏移量,实现从底部对齐到顶部对齐的平滑过渡
- 适配响应式布局,优先保障桌面端体验
修改后的代码实现
HTML 结构
<div class="content"> <div class="margin-content"> <h1> My Brand </h1> </div> <!-- 新增视差容器 --> <div class="parallax-header"> <div class="parallax-bg"></div> <img src="https://i.sstatic.net/uxvh2.png" class="header-foreground" /> </div> <div class="margin-content"> <h2>Lorem ipsum dolor sit amet..</h2> <p>..consectetur adipiscing elit. Fusce ex erat, vehicula vitae sapien vel, dignissim ornare odio.</p> </div> </div> <p style="color:white;text-align: center; position: relative; top:13px">© 2048 My Brand</p>
CSS 样式
body { background: gray; font-size: 140%; margin: 0; } .content { margin: 50px auto 0px auto; max-width: 1100px; padding-bottom: 2000px; padding-top: 30px; background-color: white; border: solid black; border-width: 0px 16px 0px 16px; } .margin-content { margin: 30px 80px 0px 100px; } /* 视差容器样式 */ .parallax-header { width: 100%; position: relative; overflow: hidden; height: auto; } .header-foreground { width: 100%; display: block; position: relative; z-index: 2; } .parallax-bg { position: absolute; top: 0; left: 0; width: 100%; /* 背景图高度设为比前景图高,可根据实际比例调整 */ height: 150%; background-image: url("https://i.sstatic.net/r6CD4.jpg"); background-size: cover; background-position: center bottom; z-index: 1; }
JavaScript 逻辑
document.addEventListener('DOMContentLoaded', function() { const parallaxContainer = document.querySelector('.parallax-header'); const parallaxBg = document.querySelector('.parallax-bg'); const foregroundImg = document.querySelector('.header-foreground'); // 计算背景图需要移动的总距离:背景图高度 - 前景图高度 let maxOffset = parallaxBg.offsetHeight - foregroundImg.offsetHeight; function updateParallax() { // 获取容器相对于视口的位置 const rect = parallaxContainer.getBoundingClientRect(); // 容器顶部超出视口的距离 const scrollOutDistance = -rect.top; // 计算滚动进度:0(初始状态)到1(完全移出视口) const scrollProgress = Math.min(Math.max(scrollOutDistance / parallaxContainer.offsetHeight, 0), 1); // 设置背景图偏移,实现从底部对齐到顶部对齐的过渡 parallaxBg.style.transform = `translateY(${ -scrollProgress * maxOffset }px)`; } // 监听滚动和窗口 resize 事件 window.addEventListener('scroll', updateParallax); window.addEventListener('resize', function() { // 窗口大小改变时重新计算最大偏移量 maxOffset = parallaxBg.offsetHeight - foregroundImg.offsetHeight; updateParallax(); }); // 初始化位置 updateParallax(); });
效果说明
- 初始状态:背景图底部与前景图底部完全对齐
- 向下滚动页面时,背景图以慢于前景图的速度向上移动,营造3D视差错觉
- 当头部区域完全移出视口时,背景图顶部与前景图顶部对齐
- 响应式适配:窗口大小改变时自动重新计算参数,保持视差效果正常
内容的提问来源于stack exchange,提问作者Johan
相关产品推荐
相关产品推荐

