You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止<dialog>元素通过Esc键关闭?

关于<dialog>元素Esc键关闭的异常问题

根据MDN文档,HTML的<dialog>元素按下Esc键时默认会触发关闭。但实际开发场景中,我们往往需要阻止这种默认行为——比如需要先让用户确认是否真的要关闭弹窗。

我们可以通过变量preventClosing来控制是否允许Esc键关闭dialog。虽然<dialog>提供了cancel事件,调用event.preventDefault()能临时阻止关闭,但该方法仅生效一次:连续按两次Esc键后,dialog还是会被强制关闭。

以下代码可复现这一问题:

复现代码

HTML

<button>打开弹窗</button>
<dialog>禁止用Esc直接关闭的弹窗</dialog>

JavaScript

const preventClosing = true;
const button = document.querySelector('button');
const dialog = document.querySelector('dialog');

button.addEventListener('click', () => {
    dialog.showModal();
});

dialog.addEventListener('cancel', (event) => {
    if (preventClosing) {
        event.preventDefault();
    }
});

内容的提问来源于stack exchange,提问作者Nighto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:31:06