基于滚动位置切换右侧固定区域图片,寻求平滑切换优化方案
滚动切换固定图片的优化方案
解决问题
实现滚动时平滑切换右侧固定区域的图片,同时简化代码逻辑,提升可维护性。
完整代码实现
HTML
<div class="wrapper"> <div class="mainCon"></div> <div class="fixedCon"> <img class="fixed-img active" src="https://c8.alamy.com/comp/2JBC70X/realistic-mayonnaise-vertical-ads-poster-with-outdoor-scenery-table-and-eggs-with-plates-and-product-package-vector-illustration-2JBC70X.jpg" /> <img class="fixed-img" src="https://img.pikbest.com/origin/06/48/91/82qpIkbEsTUQe.jpg!w700wp" /> <img class="fixed-img" src="https://www.shutterstock.com/shutterstock/photos/531750643/display_1500/stock-vector-christmas-sale-vertical-advertising-banner-531750643.jpg" /> </div> </div>
CSS
.wrapper { display: flex; width: 100%; height: 700vh; background-color: salmon; } .mainCon { width: 70%; height: 100%; background-color: blue; } .fixedCon { width: 30%; height: 100vh; position: sticky; top: 0; display: flex; align-items: center; justify-content: center; background-color: gold; } .fixed-img { position: absolute; width: 210px; height: 400px; opacity: 0; transition: opacity 0.5s ease; } .fixed-img.active { opacity: 1; }
JavaScript
const fixedImgs = document.querySelectorAll('.fixed-img'); const totalScrollHeight = document.documentElement.scrollHeight; const sectionHeight = totalScrollHeight / fixedImgs.length; window.addEventListener('scroll', () => { const currentScroll = window.scrollY; const activeIndex = Math.min(Math.floor(currentScroll / sectionHeight), fixedImgs.length - 1); fixedImgs.forEach((img, index) => { img.classList.toggle('active', index === activeIndex); }); });
核心优化点
- 平滑过渡效果:放弃
display切换,改用opacity配合CSS过渡动画,实现自然的淡入淡出,解决原代码切换生硬的问题。 - 简化定位逻辑:将右侧容器设置为
position: sticky,无需通过JS动态修改图片的fixed属性,浏览器自动维持固定位置,代码更简洁。 - 可扩展的JS逻辑:用数组批量管理图片元素,通过计算滚动位置对应的索引切换
active类,后续新增图片只需在HTML中添加,无需修改JS代码。 - 动态区间计算:根据图片数量自动平均分配滚动区间,适配不同页面高度或图片数量的变化。
内容的提问来源于stack exchange,提问作者seriously
相关产品推荐
相关产品推荐

