HTMLDialogElement: showModal() 方法
HTMLDialogElement 接口的 showModal() 方法会以模态方式显示对话框,覆盖在其他任何可能存在的对话框之上。它会显示在 顶层,并伴随有一个 ::backdrop 伪元素。与对话框位于同一文档中的元素(除了对话框本身及其后代元素)将变为惰性(如同指定了 inert 属性)。只有包含的文档会被阻止;如果对话框渲染在 iframe 中,页面的其余部分将保持交互状态。
语法
js
showModal()
参数
无。
返回值
无(undefined)。
异常
InvalidStateErrorDOMException-
如果对话框已打开且非模态(即,如果对话框已使用
HTMLDialogElement.show()打开),则会抛出此错误。
示例
打开模态对话框
以下示例展示了一个按钮,当点击该按钮时,将通过 HTMLDialogElement.showModal() 函数打开一个包含表单的模态 <dialog> 元素。打开期间,除了模态对话框的内容外,其他所有内容都将处于惰性状态。然后,您可以点击取消按钮(通过 HTMLDialogElement.close() 函数)关闭对话框,或通过提交按钮提交表单。选择取消按钮会关闭对话框,并触发一个 close 事件,而不是 cancel 事件。
HTML
html
<!-- pop-up dialog box, containing a form -->
<dialog id="favDialog">
<form method="dialog">
<p>
<label for="favAnimal">Favorite animal:</label>
<select id="favAnimal" name="favAnimal">
<option></option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</p>
<div>
<button id="cancel" type="reset">Cancel</button>
<button type="submit">Confirm</button>
</div>
</form>
</dialog>
<div>
<button id="updateDetails">Update details</button>
</div>
JavaScript
js
const updateButton = document.getElementById("updateDetails");
const cancelButton = document.getElementById("cancel");
const dialog = document.getElementById("favDialog");
dialog.returnValue = "favAnimal";
function openCheck(dialog) {
if (dialog.open) {
console.log("Dialog open");
} else {
console.log("Dialog closed");
}
}
// Update button opens a modal dialog
updateButton.addEventListener("click", () => {
dialog.showModal();
openCheck(dialog);
});
// Form cancel button closes the dialog box
cancelButton.addEventListener("click", () => {
dialog.close("animalNotChosen");
openCheck(dialog);
});
结果
规范
| 规范 |
|---|
| HTML # dom-dialog-showmodal-dev |
浏览器兼容性
加载中…
另见
- 实现此接口的 HTML 元素:
<dialog>。