目前能夠簡單實現彈出層的框架實在是多,但個人還是覺得原生js代碼實現比較具有根本性。
今天剛寫完彈出層效果,以及對彈出框的拖動效果,鏈接:demo、源碼。
js代碼總體分為三個部分:獲取節點並添加點擊事件;創建彈出層節點並設置樣式;添加鼠標移動事件。重點是后面兩個部分。
HTML/CSS
首先還是附上HTML和CSS代碼,樣式寫的有些復雜,純屬個人強迫症犯了。。。需要注意的就是position和z-index兩個樣式。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>彈出層效果</title> 6 <style> 7 *{margin: 0;padding: 0;} 8 button{ 9 width: 130px; 10 height: 35px; 11 margin-top: 200px; 12 margin-left: auto; 13 margin-right: auto; 14 display: block; 15 font-size: 15px; 16 border-style: none; 17 border-radius: 5px; 18 cursor: pointer; 19 background: #e1e1e1; 20 } 21 #pop_up{ 22 background: #333; 23 position: absolute; 24 opacity:0.5; 25 filter: alpha(opacity=50); 26 top:0; 27 left: 0; 28 z-index: 1000; 29 } 30 #box{ 31 position: fixed; 32 z-index: 1002; 33 } 34 .content{ 35 width:400px; 36 height:200px; 37 margin: 0 auto; 38 background:#ffffff; 39 position: relative; 40 cursor: move; 41 -moz-border-radius: 5px; 42 -webkit-border-radius: 5px; 43 border-radius: 5px; 44 } 45 #close{ 46 width: 30px; 47 height: 30px; 48 background: url("close.png") no-repeat; 49 position: absolute; 50 cursor: pointer; 51 right: 10px; 52 top: 10px; 53 } 54 </style> 55 </head> 56 <body> 57 <button id="clk">點擊查看彈窗</button> 58 </body> 59 </html
彈出層效果
1 //獲取頁面可視區高寬 2 var oWidth = document.documentElement.clientWidth; 3 var oHeight = document.documentElement.clientHeight; 4 5 //創建陰影背景節點 6 var oParent = document.createElement('div'); 7 oParent.id = 'pop_up'; 8 oParent.style.width = oWidth +'px'; 9 oParent.style.height = oHeight +'px'; 10 document.body.appendChild(oParent); 11 12 //創建彈出層節點 13 var oChild = document.createElement('div'); 14 oChild.id = "box"; 15 oChild.innerHTML = "<div class='content'><div id='close'></div></div>"; 16 document.body.appendChild(oChild); 17 18 //設置居中顯示 19 var cWidth = oChild.offsetWidth; 20 var cHeight = oChild.offsetHeight; 21 oChild.style.left=oWidth/2-cWidth/2+"px"; 22 oChild.style.top=oHeight/2-cHeight/2+"px"; 23 24 //關閉彈出層 25 var close = document.getElementById('close'); 26 close.onclick = function(){ 27 document.body.removeChild(oParent); 28 document.body.removeChild(oChild); 29 };
如果底層頁面高度超過可視區高度,應該獲取網頁正文全文高——document.body.scrollHeight,這里不再展開。
這里彈出層的思想就是進入時創建節點,包括陰影背景以及彈出框兩部分,關閉時再移除創建的節點。
彈出框拖拽效果
1 //移動彈出框 2 var move = false; 3 var _x, _y; //記錄鼠標相對彈出框的left、top 4 var x, y; //記錄彈出框相對頁面的left、top,以便判斷 5 oChild.onmousedown = function(e){ 6 move = true; 7 _x = e.pageX - parseInt(oChild.style.left); 8 _y = e.pageY - parseInt(oChild.style.top); 9 }; 10 oChild.onmousemove = function(e){ 11 if(move){ 12 x = e.pageX - _x; 13 y = e.pageY - _y; 14 if(x < 0) x = 0; 15 if(y < 0) y = 0; 16 if(x > oWidth- cWidth) x = oWidth- cWidth; 17 if(y > oHeight - cHeight) y = oHeight - cHeight; 18 oChild.style.left = x + 'px'; 19 oChild.style.top = y + 'px'; 20 } 21 }; 22 oChild.onmouseup = function() { 23 move = false; 24 }; 25 oChild.onmouseout = function() { 26 move = false; 27 };
需要注意的是這里設置了允許移動標志move;還有彈出框的定位與鼠標坐標的計算關系;另外將彈出框限制在頁面區域內。