众所周知,浏览器自带的原生弹窗很不美观,而且功能比较单一,绝大部分时候我们都会按照设计图自定义弹窗或者直接使用注入层的弹窗等等。前段时间在慕课网上看到了一个自定义弹窗的实现,自己顺便就学习尝试写了下,下面是主要的实现代码并添加了比较详细的注释,分享出来供大家参考。(代码用了ES6部分写法如需兼容低版本浏览器请把相关代码转成es5写法,后面有时间更新为一个兼容性较好的es5版本)
HTML部分:(没什么内容放置一个按钮调用函数,js中调用实例即可供参考)
& lt; !DOCTYPE html> & lt; html> & lt; head> & lt;元charset=皍tf - 8”比; & lt;元name=笆哟啊蹦谌?翱矶?设备宽度,初始=1.0”比; & lt;元http-equiv=癤-UA-Compatible”内容=癷e=边缘”比; & lt; title>自定义弹窗& lt;/title> & lt;链接rel="样式表" href=" https://www.yisu.com/zixun/alert.css " rel=巴獠縩ofollow”比; & lt;/head> & lt; body> & lt; button>单击me & lt;脚本src=" https://www.yisu.com/zixun/index.js "祝辞& lt;/script> & lt; script> document.querySelector(“按钮”).addEventListener(“点击”,()=祝辞{ 新的美元味精({ 内容:“我的自定义弹窗好了”, 类型:“成功”, 取消:函数(){ 让美元取消=new味精({ 内容:“我是取消后的回调” }) }, 确认:函数(){ 新的美元味精({内容:“我是确定后的回调”}) } }) }) & lt;/script> & lt;/body> & lt;/html>
样式部分:也放出来供参考,样式可以根据自己的设计图自行更改即可
/*弹出框最外层*/.msg__wrap { 位置:固定; 上图:50%; 左:50%; z - index: 10; 过渡:所有。3; 变换:翻译(-50%,-50%)范围(0,0); max-width: 50%; 背景:# fff; 不必:0 0 10 px # eee; 字体大小:10 px; }/*弹出框头部*/.msg__wrap .msg-header { 填充:10 px 10 px 0 10 px; 字体大小:1.8 em; } .msg__wrap .msg-header .msg-header-close-button { 浮:正确; 光标:指针; }/*弹出框中部*/.msg__wrap .msg-body { 填充:10 px 10 px 10 px 10 px; 显示:flex; }/*图标*/.msg__wrap .msg-body .msg-body-icon { 宽度:80 px; } .msg__wrap .msg-body .msg-body-icon div { 宽度:45 px; 高度:45 px; 保证金:0汽车; 行高:45 px; 颜色:# fff; border - radius: 50% - 50%; 字体大小:2 em; } .msg__wrap .msg-body .msg-body-icon .msg-body-icon-success { 背景:# 32 a323; text-align:中心; } {后.msg__wrap .msg-body .msg-body-icon .msg-body-icon-success:: 内容:“成”; } .msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong { 背景:# ff8080; text-align:中心; } {后.msg__wrap .msg-body .msg-body-icon .msg-body-icon-wrong:: 内容:“误”; } .msg__wrap .msg-body .msg-body-icon .msg-body-icon-info { 背景:# 80 b7ff; text-align:中心; } {后.msg__wrap .msg-body .msg-body-icon .msg-body-icon-info:: 内容:“注”; }/*内容*/.msg__wrap .msg-body .msg-body-content { min-width: 200 px; 字体大小:1.5 em; 单词分割:打破所有; 显示:flex; 对齐项目:中心; padding-left: 10 px; box-sizing: border-box; }/*弹出框底部*/.msg__wrap .msg-footer { 填充:0 10 px 10 px 10 px; 显示:flex; flex-direction: row-reverse; } .msg__wrap .msg-footer .msg-footer-btn { 宽度:50 px; 高度:30 px; 边界:0; 颜色:# fff; 大纲:没有; 字体大小:1 em; border - radius: 2 px; margin-left: 5 px; 光标:指针; } .msg__wrap .msg-footer .msg-footer-cancel-button { background - color: # ff3b3b; } {.msg__wrap .msg-footer .msg-footer-cancel-button:活跃 background - color: # ff6f6f; } .msg__wrap .msg-footer .msg-footer-confirm-button { background - color: # 4896 f0; } {.msg__wrap .msg-footer .msg-footer-confirm-button:活跃 background - color: # 1 d5fac; }/*遮罩层*/.msg__overlay { 位置:固定; 上图:0; 右:0; 底部:0; 左:0; z - index: 5; background - color: rgba (0, 0, 0。4); 过渡:所有。3; 透明度:0; }
JS部分:下面是最主要的部分,JS方法及交互。自己封装自定义组件均可以此为参考,封装自己的组件。