如何实现页面滚动时固定div内文本自下而上位移切换的效果
实现fixed容器内滚动触发内容滑入滑出效果的方案
实现思路
- 外层fixed容器设置
overflow: hidden裁切超出内容,内部两个子元素初始分别定位在可视区和可视区下方 - 监听页面滚动事件获取滚动距离,滚动距离超过阈值时触发CSS过渡动画,控制两个子元素的Y轴偏移量
- 用CSS的
transition属性实现平滑位移效果,避免JS直接操作动画导致的卡顿
完整代码示例
HTML结构
<!-- 外层fixed定位容器 --> <div class="fixed-container"> <div class="content-item item-lorem">Lorem</div> <div class="content-item item-ipsum">Ipsum</div> </div> <!-- 撑开页面高度用于滚动测试,可根据实际页面结构删除 --> <div style="height: 200vh;"></div>
CSS样式
.fixed-container { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); width: 200px; height: 50px; overflow: hidden; border: 1px solid #eee; } .content-item { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 20px; transition: transform 0.3s ease; position: absolute; top: 0; left: 0; } .item-lorem { transform: translateY(0); } .item-ipsum { transform: translateY(100%); } /* 滚动后触发的类名 */ .fixed-container.scrolled .item-lorem { transform: translateY(-100%); } .fixed-container.scrolled .item-ipsum { transform: translateY(0); }
JS逻辑
const fixedContainer = document.querySelector('.fixed-container') // 触发动画的滚动阈值,可根据需求调整,这里设为100px const scrollThreshold = 100 window.addEventListener('scroll', () => { const scrollY = window.scrollY if (scrollY >= scrollThreshold) { fixedContainer.classList.add('scrolled') } else { // 不需要滚动回顶部时反向动画可以删除这行else逻辑 fixedContainer.classList.remove('scrolled') } })
效果说明
- 页面初始加载时,
.item-lorem显示在容器可视区域,.item-ipsum隐藏在容器底部 - 当页面滚动距离超过设定阈值时,两个元素同时触发位移:Lorem向上滑出容器,Ipsum从底部滑入可视区
- 可自行修改
transition参数调整动画速度、缓动效果,适配不同设计需求
内容的提问来源于stack exchange,提问作者Haktan
相关产品推荐
相关产品推荐

