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();//調用回調函數 } } } }