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

能否仅用纯CSS或Tailwind实现滚动时的平滑缓动效果?

能否用纯CSS/Tailwind实现实时缓动平滑滚动?

结论

可以通过**CSS滚动驱动动画(Scroll-Driven Animations)**实现类似原JS的实时缓动滚动效果,无需JavaScript。Tailwind也能通过自定义配置适配该方案。

核心原理

原JS代码的逻辑是:监听视口滚动位置,通过requestAnimationFrame实时更新内容容器的transform: translateY(),让内容滚动滞后于视口滚动,形成缓动效果。CSS滚动驱动动画可直接将滚动进度绑定到动画属性,实现完全一致的滞后偏移逻辑。

纯CSS实现方案

以下是对原JS效果的精准复刻代码:

body {
  margin: 0;
  overflow-y: scroll;
  height: 100vh;
}

.js-scroll {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  /* 绑定视口滚动进度作为动画时间线 */
  animation: smooth-scroll linear;
  animation-timeline: scroll(root);
}

/* 定义缓动动画:模拟原JS的滞后滚动逻辑 */
@keyframes smooth-scroll {
  from {
    transform: translateY(0);
  }
  to {
    /* 这里的10vh对应原JS的speed参数,数值越小缓动效果越明显 */
    transform: translateY(calc(-100% + 10vh));
  }
}

调整缓动强度

原JS中的speed参数控制缓动快慢,对应CSS中可调整@keyframes里的偏移比例:

  • 数值越小(如calc(-100% + 5vh)):内容滞后越多,缓动效果越强
  • 数值越大(如calc(-100% + 20vh)):内容越接近正常滚动,缓动效果越弱

Tailwind实现方案

Tailwind无内置滚动驱动动画工具类,但可通过自定义配置实现:

  1. 在tailwind.config.js中添加自定义动画和工具类:
module.exports = {
  theme: {
    extend: {
      animation: {
        'smooth-scroll': 'smooth-scroll linear',
      },
      keyframes: {
        'smooth-scroll': {
          'from': { transform: 'translateY(0)' },
          'to': { transform: 'translateY(calc(-100% + 10vh))' },
        },
      },
    },
  },
  plugins: [
    function({ addUtilities }) {
      addUtilities({
        '.animation-timeline-scroll': {
          'animation-timeline': 'scroll(root)',
        },
      });
    },
  ],
}
  1. 在HTML中使用:
<body class="m-0 h-screen overflow-y-scroll">
  <div class="fixed top-0 left-0 w-full animate-smooth-scroll animation-timeline-scroll">
    <!-- 你的页面内容 -->
  </div>
</body>

注意事项

  • CSS滚动驱动动画目前支持现代浏览器(Chrome 115+、Firefox 117+、Safari 16.4+),如需兼容旧浏览器,仍需回退到JS方案
  • 原JS中设置body.style.height的逻辑,在纯CSS方案中由position: fixed的容器自动适配,无需额外配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:05:15