dialog 简介
HTML <dialog> 元素表示一个对话框或其他交互式组件,例如一个可关闭警告、检查器或者窗口。
下面的示例会渲染一个非模态对话框。在对话框激活的状态下,点击“OK”按钮将会关闭对话框。
<dialog open> <p>Greetings, one and all!</p> <form method="dialog"> <button>OK</button> </form> </dialog>
解释:
- open 指示这个对话框是激活的和能互动的。当没有设置 open 属性时,对话框不应该显示给用户。推荐使用 .show() 或 .showModal() 方法来渲染对话框,而不是使用 open 属性。
- 表单上的 method=dialog 属性,如果表单在dialog元素中,提交时就会触发关闭对话框,button 的 type 属性必须是 'submit'。当提交表单时,对话框的 returnValue 属性将会等于表单中被使用的提交按钮的 value。
- ::backdrop CSS 伪元素可用于给使用 HTMLDialogElement.showModal() 显示的 <dialog> 元素背景添加样式,例如在对话框被打开激活时,调暗背景中不可访问的内容。
- 当使用Esc键取消<dialog>时,将同时触发 cancel 和 close 事件。
dialog 的方法
dialog.show() // Displays the dialog element. dialog.showModal() // Displays the dialog element and makes it the top-most modal dialog. // This method honors the autofocus attribute. dialog.close([ result ]) // Closes the dialog element. // The argument, if provided, provides a return value. dialog.returnValue [ = result ] // Returns the dialog's return value. // Can be set, to update the return value.
再来看一个更详细的例子:
<dialog id="favDialog"> <form method="dialog"> <p> 这是对话框中的内容 <input type="text" name="test"> </p> <div> <button type="button">无反应</button> <button type="submit" value="这是表单按钮值">提交</button> <button type="button" id="cancel">取消</button> </div> </form> </dialog> <button class="open">打开对话框</button>
var dialog = document.querySelector('#favDialog'); dialogPolyfill.registerDialog(dialog); document.querySelector('.open').addEventListener('click', e=>{ dialog.show(); }); document.querySelector('.showModal').addEventListener('click', e=>{ dialog.showModal(); }); document.querySelector('#cancel').addEventListener('click', e=>{ let textValue = document.querySelector('input[name="test"]').value; dialog.close(textValue); }); dialog.addEventListener("close", () => { console.log('dialog 的 returnValue 是: ', dialog.returnValue); }); dialog.addEventListener("cancel", () => { console.log('cancel: ', dialog.returnValue); });
dialog 的兼容性
最新的浏览器都支持 dialog,如果遇到比如 Safari 15.4 浏览器以下的版本,可以使用谷歌官方的 dialog-polyfill。
<head> <link rel="stylesheet" type="text/css" href="dist/dialog-polyfill.css" /> </head> <body> <dialog> I'm a dialog! <form method="dialog"> <input type="submit" value="Close" /> </form> </dialog> <script src="dist/dialog-polyfill.js"></script> <script> var dialog = document.querySelector('dialog'); dialogPolyfill.registerDialog(dialog); // Now dialog always acts like a native <dialog>. dialog.showModal(); </script> </body>
参考:
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/dialog
https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement
https://github.com/GoogleChrome/dialog-polyfill
https://googlechrome.github.io/dialog-polyfill/
https://zhuanlan.zhihu.com/p/602461069
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏