手风琴移动菜单
移动端手风琴菜单:点一级菜单展开二级,其它已展开的自动收起,节省屏幕空间。逻辑就是点击 toggle 加 .open,配合 max-height 过渡形成手风琴动画。
要点:max-height 设一个足够大的值(如 400px)做“从 0 展开”的过渡(height:auto 无法过渡);箭头用 transform: rotate 跟随状态翻转。
- 点击 toggle .open;max-height 0 ↔ 大值实现展开过渡
- 箭头跟随旋转:.open .arrow { transform: rotate(90deg) }
- 可用 accordion 模式(同时只开一个)或互不干扰模式
HTML
<style> #acc { max-width: 320px; margin: 20px auto; font-family: sans-serif; } #acc .grp { border: 1px solid #eee; border-radius: 10px; margin-bottom: 8px; overflow: hidden; } #acc .grp > button { width: 100%; padding: 12px 16px; border: none; background: #faf7ff; text-align: left; cursor: pointer; font-size: 14px; } #acc .sub { max-height: 0; overflow: hidden; transition: max-height .3s ease; } #acc .grp.open .sub { max-height: 200px; } #acc .arrow { float: right; transition: transform .3s ease; color: #d2a8ff; } #acc .grp.open .arrow { transform: rotate(90deg); } #acc .sub a { display: block; padding: 9px 28px; color: #555; text-decoration: none; font-size: 13px; } #acc .sub a:hover { background: #f0e6ff; } </style> <div id="acc"> <div class="grp"><button>前端基础<span class="arrow">▶</span></button> <div class="sub"><a href="#">HTML</a><a href="#">CSS</a><a href="#">JavaScript</a></div></div> <div class="grp"><button>框架与工具<span class="arrow">▶</span></button> <div class="sub"><a href="#">Vue</a><a href="#">React</a><a href="#">工程化</a></div></div> </div> <script> document.querySelectorAll('#acc .grp > button').forEach(function (btn) { btn.addEventListener('click', function () { var grp = btn.parentNode, was = grp.classList.contains('open'); document.querySelectorAll('#acc .grp').forEach(function (g) { g.classList.remove('open'); }); if (!was) grp.classList.add('open'); // 手风琴:只开一个 }); }); </script>
本节要点手风琴 = max-height 过渡 + toggle .open;箭头 rotate 跟随;手风琴模式同一时间只开一个。




