模态框 Modal
模态框(Modal):点击按钮弹出对话框,背景遮罩点击关闭,内部按钮可确认/取消。结构:遮罩 + 对话框,用 .show 控制显隐,配合 opacity/transform 过渡。
完整模态框的四个细节:打开锁 body 滚动、Esc 关闭、焦点管理(关闭后焦点回触发按钮)、aria-dialog 标记可访问性。
- 打开加 .show:遮罩淡入、对话框从下浮起(transition)
- Esc 关闭 + 遮罩点击关闭;body overflow 锁滚动
- 关后把焦点还给触发按钮(可访问性)
HTML
<style> #mBtn { padding: 10px 26px; border: none; border-radius: 8px; background: #a371f7; color: #fff; cursor: pointer; } #mMask { position: fixed; inset: 0; background: rgba(0,0,0,.45); display: flex; align-items: center; justify-content: center; opacity: 0; visibility: hidden; transition: .25s ease; } #mMask.show { opacity: 1; visibility: visible; } #mBox { width: min(340px, 88vw); background: #fff; border-radius: 14px; padding: 24px; transform: translateY(18px) scale(.95); transition: .25s ease; box-shadow: 0 20px 60px rgba(0,0,0,.25); } #mMask.show #mBox { transform: none; } #mBox h3 { margin: 0 0 8px; } #mBox p { color: #666; font-size: 14px; } #mBox .ops { text-align: right; margin-top: 18px; } #mBox .ops button { padding: 7px 18px; border-radius: 8px; border: none; cursor: pointer; } #mBox .ok { background: #a371f7; color: #fff; } #mBox .no { background: #f0e6ff; color: #333; margin-right: 8px; } </style> <button id="mBtn">打开对话框</button> <div id="mMask"> <div id="mBox" role="dialog" aria-modal="true"> <h3>确认操作?</h3> <p>这是一个模态框:Esc 关、点遮罩关、关后焦点回到按钮。</p> <div class="ops"><button class="no">取消</button><button class="ok">确定</button></div> </div> </div> <script> var mask = document.getElementById('mMask'), btn = document.getElementById('mBtn'); function open() { mask.classList.add('show'); document.body.style.overflow = 'hidden'; } function close() { mask.classList.remove('show'); document.body.style.overflow = ''; btn.focus(); } btn.addEventListener('click', open); mask.addEventListener('click', function (e) { if (e.target === mask) close(); }); mask.querySelectorAll('.ops button').forEach(function (b) { b.addEventListener('click', close); }); document.addEventListener('keydown', function (e) { if (e.key === 'Escape') close(); }); </script>
本节要点模态框 = 遮罩 + 框 + 显隐类;四细节:锁滚、Esc、遮罩关、焦点回。




