基于Framer Motion实现文字轮换动画的技术问题求助
文字轮换循环动画优化方案
核心问题解决思路
- 替换父容器的
display: inline为inline-block,既能保持行内布局特性,又能通过Chakra的mx属性轻松控制与前置文字的间距; - 移除
position: absolute,给父容器设置overflow: hidden和适配字体的高度,配合Framer Motion的动画变体实现文字上下切换,让元素留在文档流中,避免布局脱离问题。
修改后的完整代码
import { Box, Center, chakra, ChakraProvider, Heading, Text } from "@chakra-ui/react"; import { AnimatePresence, motion } from "framer-motion"; import * as React from "react"; import { createRoot } from "react-dom/client"; const MotionSpan = motion(chakra.span); interface TextLoopProps { texts: string[]; } const TextLoop: React.FC<TextLoopProps> = ({ texts }) => { const [index, setIndex] = React.useState<number>(0); React.useEffect(() => { const timer = setTimeout(() => { setIndex(prev => (prev + 1) % texts.length); }, 3000); return () => clearTimeout(timer); }, [texts]); return ( <Box display="inline-block" overflow="hidden" h="1.2em" mx={2}> <AnimatePresence initial={false}> <MotionSpan key={index} variants={{ enter: { translateY: "100%", opacity: 0 }, exit: { translateY: "-100%", opacity: 0 }, animate: { translateY: 0, opacity: 1 } }} initial="enter" animate="animate" exit="exit" transition={{ translateY: { type: "spring", stiffness: 300, damping: 200 }, opacity: { duration: 0.3 } }} display="block" > {texts[index]} </MotionSpan> </AnimatePresence> </Box> ); }; function App() { return ( <Center flexDirection="column" h="100vh" w="100vw"> <Box> <Heading> <Text as="span">Secure access</Text> <br /> <Text as="span">for</Text> <TextLoop texts={["mice", "sheep", "cows"]} /> </Heading> <Heading mt={4}> <Text as="span">But not</Text> <TextLoop texts={["cats", "goats", "bulls"]} /> </Heading> </Box> </Center> ); } const rootElement = document.getElementById("root"); const root = createRoot(rootElement); root.render( <React.StrictMode> <ChakraProvider> <App /> </ChakraProvider> </React.StrictMode> );
关键改动说明
- 父容器优化:
inline-block保留行内布局的同时支持间距控制,overflow: hidden隐藏动画时的超出部分,h="1.2em"根据字体大小设置适配高度; - 动画逻辑调整:用
translateY的百分比值实现上下滑入滑出,无需绝对定位,让元素在文档流中正常占位; - 定时器优化:添加清理函数避免内存泄漏,用函数式更新
setIndex减少依赖项。
内容的提问来源于stack exchange,提问作者Amos
相关产品推荐
相关产品推荐

