1.介绍
要使用对话框组件,您必须使用支持对话框元素的浏览器。在撰写本文时,只有Chrome和Opera有本地支持。对于其他浏览器,您需要包含对话框填充或创建自己的。
一旦你有对话支持创建一个对话框元素。使用polyfill时的元素必须是body元素的子元素。在该容器中,添加一个内容元素与类mdl-dialog__content。添加你的内容,然后用类mdl-dialog__actions创建一个操作容器。最后,为了标记,在这个容器中添加按钮来触发对话功能。
注意:对话框使用HTML <dialog>元素,它目前对跨浏览器的支持非常有限。 为了确保所有现代浏览器的支持,请考虑使用polyfill或创建自己的。 MDL中没有包含polyfill。
2.配置选项
类名 | 效果 | 其他 |
mdl-dialog | 定义容器为一个MDL对话框组件 | 必需 |
mdl-dialog__title | 定义对话框内部的标题样式 | 可选 |
mdl-dialog__content | 定义对话框内容样式 | 内容样式必需 |
mdl-dialog__actions | 定义对话框的行为样式 | 行为容器必需 |
mdl-dialog__actions--full-width | 对话框行为宽度占满 | 可选 |
3.应用举例
3.1.一个简单的对话框
<body> <button id="show-dialog" type="button" class="mdl-button">Show Dialog</button> <dialog class="mdl-dialog"> <h4 class="mdl-dialog__title">Allow data collection?</h4> <div class="mdl-dialog__content"> <p> Allowing us to collect data will let us get you the information you want faster. </p> </div> <div class="mdl-dialog__actions"> <button type="button" class="mdl-button">Agree</button> <button type="button" class="mdl-button close">Disagree</button> </div> </dialog> <script> var dialog = document.querySelector('dialog'); var showDialogButton = document.querySelector('#show-dialog'); if (! dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showDialogButton.addEventListener('click', function() { dialog.showModal(); }); dialog.querySelector('.close').addEventListener('click', function() { dialog.close(); }); </script> </body>
3.2.行为按钮占满对话框宽度
<body> <button type="button" class="mdl-button show-modal">Show Modal</button> <dialog class="mdl-dialog"> <div class="mdl-dialog__content"> <p> Allow this site to collect usage data to improve your experience? </p> </div> <div class="mdl-dialog__actions mdl-dialog__actions--full-width"> <button type="button" class="mdl-button">Agree</button> <button type="button" class="mdl-button close">Disagree</button> </div> </dialog> <script> var dialog = document.querySelector('dialog'); var showModalButton = document.querySelector('.show-modal'); if (! dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showModalButton.addEventListener('click', function() { dialog.showModal(); }); dialog.querySelector('.close').addEventListener('click', function() { dialog.close(); }); </script> </body>