仅当文本超出Div区域时实现乒乓式滚动动画的方案咨询
实现固定区域内长文本的乒乓式滚动动画
需求明确:固定宽度的文本容器,当目的地名称文本过长超出容器时,实现乒乓式左右滑动动画(文本来回移动,而非传统marquee滚动完全部内容后重启)。以下提供两种更优的实现方案,替代原jQuery版本:
方案一:纯CSS + 轻量JS检测(性能最优,无依赖)
核心思路:用CSS @keyframes 实现左右移动动画,通过animation-direction: alternate实现来回乒乓效果;仅当文本宽度超出容器时才添加动画类,避免短文本无效动画。
代码实现
CSS
.destination { height: 40px; width: 250px; left: 0; white-space: nowrap; overflow: hidden; font-size: 32px; position: absolute; /* 基础布局优化 */ display: flex; align-items: center; } .row1 { top: 0; } .row2 { top: 100px; } /* 乒乓滚动动画 */ @keyframes pingPongScroll { 0% { transform: translateX(0); } 100% { transform: translateX(calc(-100% + 250px)); } /* 移动到文本右侧刚好露出容器边缘 */ } /* 动画触发类:仅长文本添加 */ .scroll-active { animation: pingPongScroll 3s linear infinite alternate; }
HTML
<div class="destination row1">Short name</div> <div class="destination row2">Long destination name that needs scrolling</div>
轻量JS检测(判断是否添加动画)
document.querySelectorAll('.destination').forEach(el => { // 对比容器宽度和文本实际宽度 if (el.scrollWidth > el.offsetWidth) { el.classList.add('scroll-active'); } });
说明
- 动画时长
3s可根据需求调整,linear保证匀速滑动 alternate属性让动画执行到终点后反向播放,实现乒乓效果- JS仅做一次初始化检测,无持续性能消耗
方案二:原生JS精细控制(适合动态调整场景)
如果需要更灵活的控制(比如动态修改文本后重新计算、调整滑动速度),可以用原生JS结合requestAnimationFrame实现:
代码实现
CSS
.destination { height: 40px; width: 250px; left: 0; white-space: nowrap; overflow: hidden; font-size: 32px; position: absolute; display: flex; align-items: center; } .row1 { top: 0; } .row2 { top: 100px; } .destination .text-content { position: relative; /* 用于控制位移 */ }
HTML
<div class="destination row1"> <span class="text-content">Short name</span> </div> <div class="destination row2"> <span class="text-content">Long destination name that needs scrolling</span> </div>
JS逻辑
function initPingPongScroll(containerSelector) { document.querySelectorAll(containerSelector).forEach(container => { const content = container.querySelector('.text-content'); if (!content) return; const containerWidth = container.offsetWidth; const contentWidth = content.offsetWidth; // 文本未超出容器,无需滚动 if (contentWidth <= containerWidth) return; let position = 0; let direction = -1; // -1左移,1右移 const speed = 0.5; // 滑动速度,数值越大越快 function animate() { // 计算边界:左移到文本右侧露出容器,右移回到初始位置 const maxLeft = -(contentWidth - containerWidth); if (position <= maxLeft) direction = 1; if (position >= 0) direction = -1; position += direction * speed; content.style.transform = `translateX(${position}px)`; requestAnimationFrame(animate); } animate(); }); } // 初始化滚动 initPingPongScroll('.destination');
说明
- 支持动态修改文本后重新调用
initPingPongScroll刷新动画 requestAnimationFrame保证动画流畅度,性能优于定时器
内容的提问来源于stack exchange,提问作者JDCov87
相关产品推荐
相关产品推荐

