滚动替换Div、终止滚动:jQuery/JavaScript侧滑切换效果开发需求
实现类似滚动切换视图的侧边滑入效果
我帮你梳理了一个简洁的实现方案,完全适配非WordPress站点,支持多张图片的侧边滑入切换,而且不会有复杂动画的冗余代码,核心逻辑和你想要的效果完全匹配:
1. HTML 结构
先搭好基础结构,包含一个顶部区域和多个全屏内容视图:
<header class="top-section"> <!-- 这里放你的顶部内容,比如导航、logo等 --> <h1>顶部区域</h1> </header> <div class="viewport-container"> <section class="view active" data-index="0"> <img src="your-image-1.jpg" alt="视图1"> </section> <section class="view" data-index="1"> <img src="your-image-2.jpg" alt="视图2"> </section> <section class="view" data-index="2"> <img src="your-image-3.jpg" alt="视图3"> </section> <!-- 可以无限添加更多视图 --> </div>
2. CSS 样式
设置全屏布局和滑入动画,让每个视图默认隐藏在右侧,激活时滑入:
* { margin: 0; padding: 0; box-sizing: border-box; } body { overflow-x: hidden; } .top-section { height: 100vh; display: flex; align-items: center; justify-content: center; background: #f5f5f5; } .viewport-container { position: relative; width: 100vw; } .view { position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; transform: translateX(100%); transition: transform 0.5s ease-in-out; } .view.active { position: relative; transform: translateX(0); } .view img { width: 100%; height: 100%; object-fit: cover; } /* 动画过程中锁定滚动的类 */ .scroll-locked { overflow: hidden; height: 100vh; }
3. JavaScript 逻辑
监听滚动事件,判断触发条件,实现视图切换和滚动锁定:
const topSection = document.querySelector('.top-section'); const views = document.querySelectorAll('.view'); let currentIndex = 0; let isAnimating = false; const scrollThreshold = window.innerHeight * 0.2; // 触发切换的最小滚动距离,可自定义 window.addEventListener('scroll', () => { // 动画进行中时,直接跳过滚动监听 if (isAnimating) return; // 判断是否已经离开顶部区域 const topSectionBottom = topSection.getBoundingClientRect().bottom; if (topSectionBottom > 0) return; // 计算滚动差值,判断是否达到触发阈值 const scrollDelta = window.scrollY - (window.previousScrollY || 0); window.previousScrollY = window.scrollY; // 只处理向下滚动的切换(需要向上切换的话,复制逻辑改方向即可) if (scrollDelta < scrollThreshold) return; // 还有下一个视图时,执行切换 if (currentIndex < views.length - 1) { isAnimating = true; document.body.classList.add('scroll-locked'); // 移除当前视图的激活状态 views[currentIndex].classList.remove('active'); // 更新索引并激活下一个视图,触发滑入动画 currentIndex++; views[currentIndex].classList.add('active'); // 动画完成后解锁滚动,修正滚动位置 setTimeout(() => { isAnimating = false; document.body.classList.remove('scroll-locked'); window.scrollTo(0, topSection.offsetHeight + (currentIndex * window.innerHeight)); }, 500); // 时长和CSS中的transition保持一致 } });
关键细节说明
- 滚动阈值:
scrollThreshold设为视口高度的20%,可以避免轻微滚动就触发切换,你可以根据体验调整数值。 - 多视图适配:只要在
.viewport-container里新增<section class="view">元素,JS会自动识别数量,无需修改逻辑。 - 滚动锁定:通过
isAnimating状态和scroll-locked类,确保动画过程中不会连续触发切换,避免混乱。 - 位置修正:动画结束后强制滚动到当前视图顶部,保证页面滚动位置和视图切换同步。
如果需要支持向上滚动切换回上一个视图,只需要在JS中添加对向上滚动的判断逻辑,调整 currentIndex 并切换 active 类即可,和向下切换的逻辑几乎一致。
内容的提问来源于stack exchange,提问作者kpollock
相关产品推荐
相关产品推荐

