求助:滚动时切换指定Div对应的固定背景图实现方案
实现滚动时切换固定背景图并移动内容块
问题说明
制作「我们的故事」板块时需要实现以下效果:
- 滚动页面时,内容div向上移动
- 当某个div到达视口中心时,平滑切换页面的固定背景图,背景图与对应div关联
修正后的完整代码
HTML
<div class="parent"> <div class="content-block" data-bg="https://picsum.photos/id/1019/1080/1920"> Content about desert </div> <div class="content-block" data-bg="https://picsum.photos/id/1015/1080/1920"> Content about mountains </div> <div class="content-block" data-bg="https://picsum.photos/id/1061/1080/1920"> Content about birds </div> </div>
CSS
.parent { /* 开启背景过渡动画 */ transition: background-image 0.8s ease-in-out; background-image: url(https://picsum.photos/id/1019/1080/1920); background-size: cover; background-repeat: no-repeat; background-position: center; background-attachment: fixed; min-height: 300vh; padding: 20vh 0; text-align: center; color: white; } .content-block { height: 50vh; padding: 20px; width: 400px; margin: 90vh auto; display: flex; align-items: center; justify-content: center; } /* 给每个内容块设置不同背景色 */ .content-block:nth-child(1) { background-color: aqua; } .content-block:nth-child(2) { background-color: skyblue; } .content-block:nth-child(3) { background-color: grey; }
JavaScript
const parent = document.querySelector('.parent'); const blocks = document.querySelectorAll('.content-block'); function checkBlockPosition() { const viewportCenter = window.innerHeight / 2; blocks.forEach(block => { const blockRect = block.getBoundingClientRect(); // 计算内容块的中心位置 const blockCenter = blockRect.top + blockRect.height / 2; // 当内容块中心到达视口中心时切换背景 if (Math.abs(blockCenter - viewportCenter) < 50) { const bgUrl = block.getAttribute('data-bg'); parent.style.backgroundImage = `url(${bgUrl})`; } }); } // 监听滚动和窗口 resize 事件 window.addEventListener('scroll', checkBlockPosition); window.addEventListener('resize', checkBlockPosition); // 页面加载时先检查一次 checkBlockPosition();
关键修改说明
- HTML部分:给每个内容块添加
data-bg属性,存储对应的背景图URL,方便JS读取 - CSS部分:
- 给
.parent添加transition属性,实现背景图平滑切换效果 - 修复原代码中
margin属性冲突的问题,统一用margin: 90vh auto控制内容块间距 - 用
min-height替代height,避免内容溢出时被截断
- 给
- JavaScript部分:
- 监听滚动和窗口大小变化事件,实时检查内容块位置
- 计算视口中心和内容块中心的位置,当两者接近时切换背景图
- 页面加载时主动触发一次检查,确保初始背景正确
内容的提问来源于stack exchange,提问作者Sohaib Ashraf
相关产品推荐
相关产品推荐

