别再用alert()做弹窗了,浏览器自带的系统级模态框太好用了!
|
admin
2024年12月19日 22:59
本文热度 1800
|
作者:TANKING,来源:https://segmentfault.com/a/1190000044660098
在很多场景下,我们都需要弹窗用于交互,一般UI框架都有模态框,如果你做一个小单页,不引入UI库,你将无法使用模态框,或者使用JavaScript自带的alert弹出提醒,或者是自己写,这都不是很便利。
dialog 是html5新增的语义化双标签,用于展示一个交互式的模态对话框。这是浏览器自带的模态框,非常好用。
来,上代码,大家一起来看看。
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dialog</title> <style> *{ padding: 0; margin: 0; } #modal { border: none; border-radius: 8px; margin: 0 auto; padding: 20px; position: fixed; top: -100%; left: 20%; transform: translateX(-50%); animation: slideIn 0.3s forwards; }
@keyframes slideIn { from { top: -100%; } to { top: 10%; } }
#modal .modal-header { width: 400px; padding: 10px 0; display: flex; border-bottom: 1px solid #eee; } #modal .modal-header .modal-title { flex: 1; font-size: 20px; } #modal .modal-content { border-bottom: 1px solid #eee; padding: 20px 0; font-size: 15px; } #modal .modal-header .modal-close { width: 50px; font-size: 23px; text-align: right; cursor: pointer; } #modal::backdrop { position: fixed; top: 0px; right: 0px; bottom: 0px; left: 0px; background: rgba(0, 0, 0, 0.2); }</style></head><body>
<button onclick="modal.showModal()">打开</button> <dialog id="modal"> <div class="modal-body"> <div class="modal-header"> <div class="modal-title">标题</div> <div class="modal-close" onclick="modal.close()">×</div> </div> <div class="modal-content"> 这是内容,这是内容。 </div> </div> </dialog></body></html>
这个模态框默认样式是非常丑的,好在可以自定义样式,我对这个默认样式进行了美化,可以说是丑小鸭变天鹅,我还加入了动画。

本文完。
该文章在 2024/12/20 10:52:26 编辑过