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

使用Framer Motion实现文本右侧入场动画时的溢出隐藏问题

Framer Motion实现文本右侧入场并隐藏初始状态的解决方法

核心问题原因

直接设置x: '100%'时,Framer Motion的x偏移是基于元素自身宽度计算的,文本仅向右移动自身宽度的距离,仍会留在父容器可视范围内;而x: '-100%'是向左移出父容器,不符合右侧入场的需求。

具体解决方案

方案1:父容器溢出隐藏 + 元素自身偏移

给文本的父容器添加overflow: hidden样式,限制超出容器的内容不可见,同时让文本初始状态向右偏移自身宽度(完全移出父容器右侧):

import { motion } from "framer-motion";

// 示例组件
const SlideInText = () => {
  return (
    {/* 父容器:限制溢出内容隐藏,宽度适配文本 */}
    <div style={{ overflow: "hidden", width: "fit-content" }}>
      <motion.span
        initial={{ x: "100%" }} // 初始向右偏移自身宽度,完全移出父容器
        animate={{ x: 0 }}      // 动画到原位置,实现从右侧入场
        transition={{ duration: 0.6, ease: "easeOut" }}
      >
        这是从右侧滑入的文本
      </motion.span>
    </div>
  );
};

方案2:绝对定位 + 父容器相对定位

如果需要文本在全屏容器内从右侧入场,可用绝对定位让文本初始时完全移出可视区域:

import { motion } from "framer-motion";

const FullWidthSlideIn = () => {
  return (
    {/* 父容器:相对定位作为文本的定位基准 */}
    <div style={{ position: "relative", width: "100%", height: "50px" }}>
      <motion.h2
        style={{ position: "absolute" }}
        initial={{ x: "100%" }} // 初始向右偏移父容器宽度,完全移出右侧
        animate={{ x: 0 }}
        transition={{ duration: 0.8 }}
      >
        全屏右侧入场文本
      </motion.h2>
    </div>
  );
};

注意事项

  • 确保父容器的overflow: hidden生效,避免文本溢出后仍可视;
  • 若使用百分比偏移,需明确偏移的参考基准(元素自身/父容器),必要时可用具体数值(如x: 300px)或calc()计算偏移量;
  • 调整transition参数可优化动画的速度和缓动效果,让入场更自然。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:20:36