js创建弹框(提示框,待确认框)
Posted 兼容IE8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js创建弹框(提示框,待确认框)相关的知识,希望对你有一定的参考价值。
html,body,div,h1,h2,h3,h4,h5,h6,p,table,form,label,ol,ul,li,dl,dt,dd,img,p{margin:0; padding:0;} 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: 0; top: 0;z-index: 999;} .box{width: 300px; height: 300px; background: #ccc; position: fixed; left: 50%; top: 50%;margin:-150px 0 0 -150px; z-index: 9999; 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创建弹框(提示框,待确认框)的主要内容,如果未能解决你的问题,请参考以下文章