必须调用showmodal()才能显示并激活模态行为,默认隐藏且不响应css或click;showmodal()自动禁背景、锁焦点、支持esc和点击遮罩关闭,而show()仅为非模态浮层。

点击按钮触发弹窗的最简实现
直接用 onclick 绑定 alert() 或 confirm() 是最快路径,但仅适合调试或极简提示。真实项目中几乎不用——它阻塞主线程、无法定制样式、不支持键盘操作(如 ESC 关闭),且现代框架普遍禁用内联事件。
推荐做法是用原生 DOM 控制一个自定义 <dialog></dialog> 元素:
<button id="openBtn">打开弹窗</button> <dialog id="myDialog"><p>这是弹窗内容</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5806" title="html-deploy"><img src="https://img.php.cn/upload/skill/000/000/081/179066538882434.jpg" alt="html-deploy" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill5806" title="html-deploy" class="overflowclass">html-deploy</a> <p class="overflowclass">使用 htmlcode.fun 将 HTML 内容或文件部署到网页,适用于用户要求“部署到网页”“托管此 HTML”“生成此前端...的实时链接”等场景。</p> </div> <a rel="nofollow" href="/xiazai/skill5806" title="html-deploy" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <button id="closeBtn">关闭</button> </dialog>
<dialog></dialog> 原生支持 showModal() 和 close(),自动处理焦点捕获和 backdrop 点击关闭,比手写 display: none/block 更可靠。
为什么 document.getElementById("myDialog").showModal() 报错?
常见错误是调用 showModal() 时元素还没被浏览器解析,或 <dialog></dialog> 不在 body 直接子级(某些 SSR 框架会嵌套 wrapper div)。报错信息通常是:Failed to execute 'showModal' on 'HTMLDialogElement': The element is not in a Document。
解决办法:
- 确保脚本放在
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










