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

Framer Motion whileInView动画在overflow-hidden容器内不触发求助

解决Framer Motion文字滑入动画不触发问题

问题分析

你的代码中,whileInView 绑定在 <motion.h1> 上,但它被包裹在 overflow-hidden 的容器内,可能因元素尺寸或视图检测范围问题导致动画未触发;同时每个字符的外层容器没有固定宽度,overflow-hidden 无法正确裁剪超出部分,也会影响动画表现。

修复步骤

  • 给字符容器设置固定宽度:没有固定宽度时,overflow-hidden 无法生效,文字滑入时不会被容器裁剪,需设置与字体大小匹配的宽度。
  • 调整视图检测目标:将视图检测配置移到字符外层容器上,确保容器进入视图时触发子元素动画——避免子元素初始在容器外无法被检测到的问题。
  • 优化动画初始状态:用百分比值替代固定像素的位移量,适配不同屏幕和字体尺寸。

修复后的代码

const AnimatedText: FC<AnimatedTextProps> = ({ text }) => {
  return (
    <div className="flex justify-center items-center border border-green-500">
      {text.split("").map((char, index) => (
        <motion.div
          key={index}
          className="overflow-hidden flex items-center justify-center"
          whileInView={{ opacity: 1 }}
          viewport={{ once: true, amount: 0.3 }}
          style={{ width: "20vw" }}
        >
          <motion.h1
            initial={{ x: "-100%" }}
            animate={{ x: 0 }}
            transition={{
              duration: 0.8,
              delay: 0.1 + index * 0.2,
              ease: "easeOut",
            }}
            className="m-0 text-main-coal text-[20vw] uppercase"
          >
            {char}
          </motion.h1>
        </motion.div>
      ))}
    </div>
  );
};

额外优化提示

  • 如果动画仍不触发,可调整 viewport 的 amount 值(比如设为0.1,即容器10%进入视图就触发)。
  • 也可以给最外层容器添加 ref,使用 useInView 钩子手动控制动画状态,实现更灵活的触发逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:26:07