如何在Framer Motion逐字文本动画中保留单词间距?
解决Framer Motion逐字动画中空格丢失的问题
你遇到的问题根源在于:split('')确实把空格拆进了字符数组,但用motion.div(块级元素)包裹单个空格时,浏览器不会正确渲染空格的宽度,导致视觉上空格消失。以下是几种可行的解决方法:
方法一:改用行内元素(推荐)
把motion.div换成motion.span,span是行内元素,能正常保留空格的宽度:
import { motion } from 'framer-motion' type Props = { text: string } function AnimatedText({ text }: Props) { const characters = text.split('') return ( <> <div className='flex'> {characters.map((char, index) => ( <motion.span key={index} initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.04 * index }} > {char} </motion.span> ))} </div> </> ) } export default AnimatedText
方法二:手动替换空格为非换行空格
如果坚持要用div,可以把空格替换成\u00A0(非换行空格),强制浏览器渲染空格宽度:
import { motion } from 'framer-motion' type Props = { text: string } function AnimatedText({ text }: Props) { const characters = text.split('') return ( <> <div className='flex'> {characters.map((char, index) => ( <motion.div key={index} initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.04 * index }} > {char === ' ' ? '\u00A0' : char} </motion.div> ))} </div> </> ) } export default AnimatedText
方法三:给空格容器设置最小宽度
针对空格的容器单独设置最小宽度,确保空格占位置:
import { motion } from 'framer-motion' type Props = { text: string } function AnimatedText({ text }: Props) { const characters = text.split('') return ( <> <div className='flex'> {characters.map((char, index) => ( <motion.div key={index} initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.04 * index }} style={{ minWidth: char === ' ' ? '0.5em' : 'auto' }} > {char} </motion.div> ))} </div> </> ) } export default AnimatedText
注:
0.5em的宽度可以根据你的字体大小调整,确保和正常空格宽度一致。
内容的提问来源于stack exchange,提问作者Bruno Bispo
相关产品推荐
相关产品推荐

