本文介绍一种轻量、高性能的纯 javascript 方案,通过监听页面滚动并计算元素在视口中的相对位置,驱动文本容器从左右两侧平滑滑入/滑出,支持自定义起始方向与响应式宽度适配。
本文介绍一种轻量、高性能的纯 javascript 方案,通过监听页面滚动并计算元素在视口中的相对位置,驱动文本容器从左右两侧平滑滑入/滑出,支持自定义起始方向与响应式宽度适配。
要实现「随滚动进度触发动画」的文本滑入效果(如城市名列表从左/右飞入),关键在于:将滚动位置映射为 0–100% 的可视进度,并据此动态更新元素的 left 或 right 偏移值。原始 jQuery 实现存在两个核心问题:
以下是优化后的现代实现方案(无 jQuery,兼容主流浏览器):
const screenHeight = window.innerHeight - item.offsetHeight;let scrollProgress = 100 - (100 / screenHeight * (item.offsetTop - window.scrollY));scrollProgress = Math.max(0, Math.min(100, scrollProgress)); // 限定在 [0, 100]
<!DOCTYPE html><html><head> <style> body { padding: 1500px 0; background: #222; margin: 0; } .wrapper { background: orange; overflow: hidden; padding: 200px 0; position: relative; } .item { background: green; height: 100px; position: absolute; top: 0; transition: none; /* 避免 CSS 过渡干扰滚动实时性 */ } .item:nth-child(1) { width: 500px; } .item:nth-child(2) { width: 2500px; } .item:nth-child(3) { width: 1000px; } .item:nth-child(4) { width: 750px; } .item:nth-child(5) { width: 1800px; } .item:nth-child(6) { width: 900px; } </style></head><body> <div class="wrapper"> <div class="item" data-position="left"></div> <div class="item" data-position="right"></div> <div class="item" data-position="left"></div> <div class="item" data-position="left"></div> <div class="item" data-position="right"></div> <div class="item" data-position="right"></div> </div> <script> const run = () => { const wrappers = document.querySelectorAll('.wrapper'); if (!wrappers.length) return; const updateItems = () => { wrappers.forEach(wrapper => { const items = wrapper.querySelectorAll('.item'); if (!items.length) return; items.forEach(item => { // 检查 wrapper 是否在视口垂直范围内 const wrapperTop = wrapper.offsetTop; const wrapperBottom = wrapperTop + wrapper.offsetHeight; const scrollY = window.scrollY; const viewportHeight = window.innerHeight; if (wrapperTop > scrollY + viewportHeight || wrapperBottom < scrollY) return; const position = item.getAttribute('data-position'); if (!position) return; // 关键:计算宽度缩放因子(适配不同长度文本) const faktor = (window.innerWidth + item.offsetWidth) / window.innerWidth; const screenHeight = viewportHeight - item.offsetHeight; // 计算当前 item 的滚动进度(0~100) let scrollProgress = 100 - (100 / screenHeight * (item.offsetTop - scrollY)); scrollProgress = Math.max(0, Math.min(100, scrollProgress)); // 计算起始偏移(vw 单位) let startPos = 100 - 100 * faktor; if (position === 'right') { startPos = 100 * faktor - (100 + 100 * faktor); } // 应用动态偏移 const progress = startPos + scrollProgress * faktor; item.style[position] = `${progress}vw`; }); }); }; // 节流优化:避免高频触发(生产环境建议添加防抖) let ticking = false; const requestTick = () => { if (!ticking) { requestAnimationFrame(() => { updateItems(); ticking = false; }); ticking = true; } }; window.addEventListener('scroll', requestTick); window.addEventListener('resize', requestTick); // 响应式适配 updateItems(); // 初始化 }; run(); </script></body></html>
该方案彻底规避了 IntersectionObserver 的边界判定模糊性,以滚动坐标系为唯一依据,确保长文本、不规则容器下的动画精准同步。