HTML <dialog>
元素表示一个对话框或其他交互式组件,例如一个检查器或者窗口。
Content categories | Flow content, sectioning root |
---|---|
Permitted content | Flow content |
Tag omission | 不允许,开始标签和结束标签都不能省略。 |
Permitted parents | Any element that accepts flow content |
Permitted ARIA roles | alertdialog |
DOM interface | HTMLDialogElement |
属性
这个元素包含了全局属性。但是 tabindex
特性不能被使用在 <dialog>
元素上。
open
- 指示这个对话框是激活的和能互动的。当这个
open
特性没有被设置,对话框不应该显示给用户。
使用备注
<form>
元素可在此对话框中使用,但需要指定属性method="dialog"
。当提交表单时,对话框的returnValue
属性将会等于表单中被使用的提交按钮的value
。-
::backdrop
CSS 伪元素可用于更改<dialog>
背景元素样式,例如在对话框被打开激活时,调暗背景中不可访问的内容。仅当使用HTMLDialogElement.showModal()
显示对话框时才会绘制 backdrop 背景。
Examples
简单的例子
<dialog open>
<p>Greetings, one and all!</p>
</dialog>
高级示例
当单击“更新详细信息”按钮时,此示例打开一个包含一个表单的弹出对话框。
HTML
<!-- Simple pop-up dialog box containing a form -->
<dialog id="favDialog">
<form method="dialog">
<p><label>Favorite animal:
<select>
<option></option>
<option>Brine shrimp</option>
<option>Red panda</option>
<option>Spider monkey</option>
</select>
</label></p>
<menu>
<button value="cancel">Cancel</button>
<button id="confirmBtn" value="default">Confirm</button>
</menu>
</form>
</dialog>
<menu>
<button id="updateDetails">Update details</button>
</menu>
<output aria-live="polite"></output>
JavaScript
(function() {
var updateButton = document.getElementById('updateDetails');
var favDialog = document.getElementById('favDialog');
var outputBox = document.getElementsByTagName('output')[0];
var selectEl = document.getElementsByTagName('select')[0];
var confirmBtn = document.getElementById('confirmBtn');
// “Update details” button opens the <dialog> modally
updateButton.addEventListener('click', function onOpen() {
if (typeof favDialog.showModal === "function") {
favDialog.showModal();
} else {
alert("The dialog API is not supported by this browser");
}
});
// "Favorite animal" input sets the value of the submit button
selectEl.addEventListener('change', function onSelect(e) {
confirmBtn.value = selectEl.value;
});
// "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
favDialog.addEventListener('close', function onClose() {
outputBox.value = favDialog.returnValue + " button clicked - " + (new Date()).toString();
});
})();
结果
Which button was clicked can be determined from favDialog
’s returnValue
.
规范
规范 | 状态 | 备注 |
---|---|---|
HTML Living Standard <dialog> |
Living Standard | |
HTML 5.2 <dialog> |
Recommendation | Initial definition |
浏览器兼容性
BCD tables only load in the browser
Polyfill
Include this polyfill to provide support for older browsers.
参见
close
事件cancel
事件- HTML forms guide.
::backdrop
伪元素