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

如何创建可平滑减速停止的滑动Div?

无卡顿实现滑动元素平滑减速停止方案

你当前通过切换类名修改动画时长的方式会导致卡顿,核心原因是每次切换类名时浏览器会重新初始化动画,重置元素状态,引发视觉跳变。以下是两种更优的无卡顿实现方案:


方案一:纯CSS渐进式减速动画

无需JavaScript定时器,直接通过CSS关键帧和缓动函数定义平滑的减速曲线,让动画自然从匀速过渡到停止:

.banner {
  height: 40px;
  position: relative;
  overflow: hidden;
  font-size: 24px;
  line-height: 36px;
  min-width: 5000vw;
  /* 总时长10秒,内置渐进减速逻辑 */
  animation: bannermove 10s cubic-bezier(0, 0, 0.2, 1);
  display: flex;
  justify-content: space-between;
}

@keyframes bannermove {
  0% {
    transform: translateX(0);
    /* 前2.5秒保持匀速 */
    animation-timing-function: linear;
  }
  25% {
    transform: translateX(-12.5%);
  }
  50% {
    transform: translateX(-25%);
    /* 进入第一阶段减速 */
    animation-timing-function: cubic-bezier(0.2, 0, 0.5, 1);
  }
  75% {
    transform: translateX(-37.5%);
    /* 第二阶段进一步减速 */
    animation-timing-function: cubic-bezier(0.3, 0, 0.7, 1);
  }
  100% {
    transform: translateX(-50%);
    /* 最后阶段趋近停止 */
    animation-timing-function: cubic-bezier(0.5, 0, 1, 1);
  }
}

使用说明:直接删除原有的JavaScript定时器代码,动画会自动完成平滑减速到停止的全过程。


方案二:JavaScript手动控制位移(精细可控)

如果需要自定义减速节奏或动态调整参数,用requestAnimationFrame逐帧计算位移,全程保持状态连续:

HTML(和原代码一致)

<div id="banner" class="banner">
  <div>Dragon</div>
  <div>Element</div>
  <div>Charger</div>
  <div>ZipDrive</div>
  <div>LightHouse</div>
  <!-- 其余内容省略 -->
</div>

CSS(移除内置动画)

.banner {
  height: 40px;
  position: relative;
  overflow: hidden;
  font-size: 24px;
  line-height: 36px;
  min-width: 5000vw;
  display: flex;
  justify-content: space-between;
}

JavaScript

const banner = document.getElementById('banner');
let currentX = 0;
let speed = 2; // 初始每帧移动像素
const decelerationRate = 0.99; // 减速系数,值越小减速越平缓
const startDecelerateTime = 2500; // 2.5秒后开始减速
const stopThreshold = 0.05; // 速度低于此值时停止
let startTime = Date.now();

function animate() {
  const elapsedTime = Date.now() - startTime;
  
  // 到达指定时间后开始减速
  if (elapsedTime >= startDecelerateTime) {
    speed *= decelerationRate;
  }
  
  // 速度过低时停止动画
  if (speed < stopThreshold) return;
  
  currentX -= speed;
  banner.style.transform = `translateX(${currentX}px)`;
  
  requestAnimationFrame(animate);
}

// 启动动画
animate();

优势:可以灵活调整减速时机、速率,甚至结合用户交互动态修改逻辑,全程无卡顿。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:54:51