如何让Flip Menu在展开或收起时始终保持水平居中?
Hey there! Let's fix that centering issue for your book flip menu. From the code snippet you shared, it looks like you're building a page-turning book effect—cool stuff! To keep the menu perfectly centered whether it's expanded or collapsed, we'll focus on CSS layout controls first, then tweak your JS to avoid breaking that alignment.
核心思路
Centering stays consistent when we let CSS handle the layout instead of hardcoding positions in JS. We'll use flexbox or auto margins for reliable centering, then clean up any JS that forces left-aligned positioning.
步骤1:添加CSS居中样式
First, update your styles to lock in horizontal centering for the book container:
/* 给.book的父容器设置flex布局(如果没有父容器,直接给.book设置) */ .book-wrapper { width: 100%; display: flex; justify-content: center; align-items: center; /* 可选:如果需要垂直居中,加上min-height: 100vh; */ } .book { /* 设置固定宽度,避免翻页时容器宽度突变 */ width: 600px; /* 按需调整这个值 */ margin: 0 auto; /* 备用方案:如果flex不生效,用margin auto兜底 */ position: relative; } .scene { position: relative; /* 覆盖JS里硬写的left值,让CSS控制位置 */ left: auto !important; }
步骤2:调整JS代码,移除破坏居中的硬编码
Your prevPage function was setting .scene to left: 0px, which forced the element to stick to the left and broke centering. Let's fix that:
var currentPage = 0; $('.book') .on('click', '.active', nextPage) .on('click', '.flipped', prevPage); $('.book').hammer().on("swipeleft", nextPage); $('.book').hammer().on("swiperight", prevPage); function prevPage() { $('.flipped') .last() .removeClass('flipped') .addClass('active') .siblings('.page') .removeClass('active'); // 移除硬设的left值,保留类名用于动画即可 $('.scene').addClass('right-set'); } function nextPage() { $('.active') .removeClass('active') .addClass('flipped') .next('.page') .addClass('active'); // 补全你代码里省略的部分 // 同样移除可能存在的left设置 $('.scene').removeClass('right-set'); }
额外小提示
- Make sure your
.pageelements don't overflow the.bookcontainer—this can throw off centering. - If your flip animation relies on position shifts, use
transform: translateX()instead of changingleft—transforms don't interfere with flexbox/margin centering. - Test on different screen sizes to ensure the centering holds up in responsive scenarios.
内容的提问来源于stack exchange,提问作者sonu verma

