//放入自执行的匿名函数,避免污染全局作用域//将window和document作为参数传入,可以直接在内部获取,不用再去外部找,性能更优
(function(window,document){//构造函数
let Msg=function(options){//初始化一个弹出框
this._init(options);
}//初始化一个弹出框
Msg.prototype._init=function({content="",confirm=null,cancel=null,useHTML=false,contentStyle={},contentFontSize="1.5em"}){this.content=content;this.confirm=confirm;this.cancel=cancel;this.useHTML=useHTML;this.contentStyle=contentStyle;this.contentFontSize=contentFontSize;//生成DOM元素
this._createElement();//绑定事件
this._bind([this._el,this._overlay]);//显示
this._show([this._el,this._overlay]);
}//生成DOM元素
Msg.prototype._createElement=function(){
let wrap=document.createElement("div");
wrap.className="msg__wrap";//换行前加上转义
wrap.innerHTML='
确认删除
let contentDom=wrap.querySelector(".msg-body .msg-body-content");//用解构赋值来合并对象
const contentStyle={
contentFontSize:this.contentFontSize,
...this.contentStyle
}for(let i incontentStyle){//如果是自身的属性
if(contentStyle.hasOwnProperty(i)){//style[i]==>style.i
//i是属性名,contentStyle[i]是属性值
contentDom.style[i]=contentStyle[i];
}
}//如果使用html
if(this.useHTML){
contentDom.innerHTML=this.content;
}else{
contentDom.innerText=this.content;
}
let overlay=document.createElement("div");
overlay.className="msg__overlay";this._el=wrap;this._overlay=overlay;
}//显示
Msg.prototype._show=function([el,overlay]){
document.body.appendChild(el);
document.body.appendChild(overlay);//设置动画效果显示
//延迟实现异步效果
setTimeout(function(){
el.style.transform='translate(-50%, -50%) scale(1, 1)';
overlay.style.opacity=1;
});
}//绑定事件
Msg.prototype._bind=function([el,overlay]){
const _this=this;//隐藏事件
const hideMsg=function(){
el.style.transform='translate(-50%, -50%) scale(0, 0)';
overlay.style.opacity=0;//动画结束后移除元素(css里设置的动画时间是300ms)
setTimeout(function(){
document.body.removeChild(el);
document.body.removeChild(overlay);
},300);
}//取消事件
const cancel=function(e){//如果传入了回调,则执行回调,参数是e
_this.cancel && _this.cancel.call(this._cancel,e);
hideMsg();
}//确认事件
const confirm=function(e){
_this.confirm&&_this.confirm.call(_this.confirm,e);
hideMsg();
}//点击遮罩
overlay.addEventListener("click",hideMsg);//点击右上角叉叉
el.querySelector(".msg-header .msg-header-close-button").addEventListener("click",hideMsg);//点击取消按钮
el.querySelector(".msg-footer .msg-footer-cancel-button").addEventListener("click",cancel);//点击确认按钮
el.querySelector(".msg-footer .msg-footer-confirm-button").addEventListener("click",confirm);
}//挂到window上可全局访问
window.$Msg=Msg;
})(window,document);