使用HTML5原生对话框元素并轻松创建模态框组件
如果你不希望用户与对话框以外的其他页面元素对象进行交互,那么请使用.showModal()打开对话框而不是使用.show()。用.showModal()打开的对话框会有一个全窗口的半透明背景层,阻断用户与对话框之外的页面元素对象进行交互,同时对话框会默认显示在窗口正中间(上下左右都居中);而用.show()打开的对话框会默认显示在窗口顶部(可以通过css实现居中显示)。 关闭对话框后,close会触发一个事件。另外,用户可以通过输入“Escape”键来关闭模式对话框。这将激发cancel您可以取消使用的事件event.preventDefault()。 与表单集成使用 您可以使用form[method="dialog"]将表单与一个<dialog>元素集成使用。表单提交后,它会关闭对话框并设置dialog.returnValue到value已使用的提交按钮。 此外,您可以使用该autofocus属性在弹出对话框时自动将焦点对准对话框内的窗体控件。 例如: <!--HTML--> <dialog id ="dialog"> <form method ="dialog"> <p>你是否同意使用条款?</p> <p><textarea class ="form-control" disabled>条款要求...</textarea></p> <button type ="submit" value ="是">是</button> <button type ="submit" value ="否" autofocus>否</button> </form> </dialog> <button id="show">显示表单对话框</button> <!--script--> <script> var dialog = document.querySelector("dialog"); document.querySelector("#show").onclick = function(){ dialog.showModal(); }; //监听dialog元素的close事件 dialog.addEventListener("close", function(e){ if(this.returnValue === "是"){ alert(this.returnValue) //dosomething... }else{ alert(this.returnValue) //dosomething... }; }); </script> 浏览器兼容性 桌面浏览器只有谷歌浏览器支持dialog的完整功能(到本博文发表时),要实现跨浏览器兼容请使用dialog-polyfill。 <iframe src=http://www.jb51.net/html5/"/caniuse.com/dialog/embed" scrolling="no" allowtransparency="true" allowfullscreen="true" frameborder="0"></iframe> 参考文献 参考文章:对话框元素演示 符本人开源项目 usuallyjs函数库:https://github.com/JofunLiang/usuallyjs (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |