Framer Motion汉堡菜单移动端Y轴偏移:flexbox引发的动画异常
解决Framer Motion汉堡菜单Y轴偏移问题
问题根源
导航栏使用justify-content: space-between后,移动端切换菜单时,容器内元素的垂直布局会因为元素数量变化重新计算,导致动画过程中Y轴出现不必要的偏移,破坏了纯水平滑动的效果。
修复方案
锁定动画Y轴属性:在Framer Motion的动画变体里,明确指定Y轴始终保持0,只让X轴参与动画。示例代码:
const navItemVariants = { hidden: { x: "100%", y: 0 }, visible: { x: 0, y: 0 } }; const burgerIconVariants = { hidden: { x: 0, y: 0 }, visible: { x: "-100%", y: 0 } };固定导航栏垂直布局:给导航栏容器设置固定最小高度,同时用
align-items: center让内部元素垂直居中,避免元素显隐时垂直布局波动:.navbar { display: flex; justify-content: space-between; align-items: center; min-height: 60px; }独立导航项容器:把移动端导航项单独放到一个固定定位的容器里,让它的滑动完全不影响导航栏的垂直布局:
// 调整Navbar组件结构 <div className="mobile-nav-container"> {navItems.map((item) => ( <motion.a key={item.id} variants={navItemVariants} initial="hidden" animate={isOpen ? "visible" : "hidden"} href={item.href} > {item.label} </motion.a> ))} </div>给这个容器添加样式,确保仅在水平方向滑动:
.mobile-nav-container { position: fixed; top: 60px; /* 和导航栏高度保持一致 */ right: 0; height: calc(100vh - 60px); width: 100%; display: flex; flex-direction: column; padding: 1rem; background: #fff; }禁用自动布局动画:如果还有细微偏移,给motion元素添加
layout={false}属性,禁止Framer Motion自动处理布局变化:<motion.a key={item.id} variants={navItemVariants} initial="hidden" animate={isOpen ? "visible" : "hidden"} layout={false} href={item.href} > {item.label} </motion.a>
内容的提问来源于stack exchange,提问作者Milosz_p
相关产品推荐
相关产品推荐

