js创建弹框(提示框,待确认框)

2023-01-05,,,

html,body,div,h1,h2,h3,h4,h5,h6,p,table,form,label,ol,ul,li,dl,dt,dd,img,p{margin:; padding:;}
html,body{text-size-adjust:none;-webkit-text-size-adjust:none;-webkit-user-select:none;}
a{color:#333; text-decoration:none;}
a,input:focus,div,select{tap-highlight-color:rgba(0,0,0,0);-webkit-tap-highlight-color:rgba(0,0,0,0);}
ul,li{list-style:none;}
.overlay{width: 100%; height: 100%; background: #000; opacity: 0.5; filter: alpha(opacity=50); position: fixed; left:; top:;z-index:;}
.box{width: 300px; height: 300px; background: #ccc; position: fixed; left: 50%; top: 50%;margin:-150px 0 0 -150px; z-index:; font-size: 18px; color: #000;}
.close{width: 20px; height: 20px; background: url(icon_close.png) scroll center center no-repeat; position: absolute; right: 10px; top: 10px; cursor: pointer;}
<a href="javascript:;" class="btn" id="btn1">提示框</a>
<a href="javascript:;" class="btn" id="btn2">没有关闭按钮的确认框</a>
<a href="javascript:;" class="btn" id="btn3">确认框</a>
var oBtn = document.getElementsByTagName('a');
var body = document.body || document.getElementsByTagName('body')[0];
var isClick,timer;
var closeBtn,popus,overlay;
//兼容PC点击事件与手机触屏事件
if(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)){ //苹果手机
isClick = 'touchend'; }else if (/(Android)/i.test(navigator.userAgent)){ //安卓手机
isClick = 'touchend';
}else { //pc
isClick = 'click';
}
oBtn[0].onclick = function(){
showBox({
el:'<h1>我1.5秒后消失</h1>',
time:1500
})
}
oBtn[1].onclick = function(){
showBox({
el:'<h1>我没有关闭按钮</h1>'
}) }
oBtn[2].onclick = function(){
showBox({
el:'<h1>我是h1标签</h1>',
close:true,
closeFn:function(){
alert('这是个关闭回调函数');
}
}) }
function showBox(init){
if(!init.el){
return;
}
popus = document.createElement('div');//弹框内容
body.appendChild(popus);//body添加弹框
popus.className = 'box';
popus.innerHTML= init.el;//弹框添加内容
if(init.time){ //time代表过一段是时间消失
clearTimeout(timer)
timer=setTimeout(function(){
body.removeChild(popus);//删除弹框内容
},init.time);
}else{ //没time代表需要手动关闭弹框
overlay = document.createElement('div');//遮罩层
body.appendChild(overlay);//body添加遮罩层
overlay.className = 'overlay';
//给遮罩层按钮绑定监听事件
if(overlay.attachEvent){ //IE
overlay.attachEvent('on'+isClick,isOpen)
}else{ //标准
overlay.addEventListener(isClick,isOpen);
}
function isOpen(){
body.removeChild(overlay);//删除遮罩层
body.removeChild(popus);//删除弹框内容
}
if(init.close){ //init.close代表需要关闭按钮
closeBtn = document.createElement('span');//弹框关闭按钮
closeBtn.className = 'close';
popus.appendChild(closeBtn);//弹框内容添加弹框关闭按钮
//给关闭按钮绑定监听事件
if(closeBtn.attachEvent){ //IE
closeBtn.attachEvent('on'+isClick,isClose)
}else{ //标准
closeBtn.addEventListener(isClick,isClose);
}
function isClose(){
body.removeChild(overlay);//删除遮罩层
body.removeChild(popus);//删除弹框内容
init.closeFn();//调用回调函数
}
}
}
}

js创建弹框(提示框,待确认框)的相关教程结束。

《js创建弹框(提示框,待确认框).doc》

下载本文的Word格式文档,以方便收藏与打印。