You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于滚动位置切换右侧固定区域图片,寻求平滑切换优化方案

滚动切换固定图片的优化方案

解决问题

实现滚动时平滑切换右侧固定区域的图片,同时简化代码逻辑,提升可维护性。


完整代码实现

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);
  });
});

核心优化点

  1. 平滑过渡效果:放弃display切换,改用opacity配合CSS过渡动画,实现自然的淡入淡出,解决原代码切换生硬的问题。
  2. 简化定位逻辑:将右侧容器设置为position: sticky,无需通过JS动态修改图片的fixed属性,浏览器自动维持固定位置,代码更简洁。
  3. 可扩展的JS逻辑:用数组批量管理图片元素,通过计算滚动位置对应的索引切换active类,后续新增图片只需在HTML中添加,无需修改JS代码。
  4. 动态区间计算:根据图片数量自动平均分配滚动区间,适配不同页面高度或图片数量的变化。

内容的提问来源于stack exchange,提问作者seriously

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 22:46:33