這是一個用js實現彈出一個層,讓層居中,並且可以拖拽喔,代碼如下,復制粘貼后,保存成html,就可以直接看到效果喔 ,雖然界面有點丑,但功能實現了,希望大家一起來改進
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> var x0 = 0, y0 = 0, x1 = 0, y1 = 0; var moveable = false; function startDrag(obj) { if (event.button == 1) { //0 沒按鍵 1 按左鍵 2 按右鍵 3 按左和右鍵 4 按中間鍵 5 按左和中間鍵 6 按右和中間鍵 7 按所有的鍵 obj.setCapture(); ////設置捕獲范圍 var win = obj.parentNode; //得到層的父節點 x0 = event.clientX; y0 = event.clientY; x1 = parseInt(win.offsetLeft); y1 = parseInt(win.offsetTop); moveable = true; } } function drag(obj) { if (moveable) { var win = obj.parentNode; var bodywidth = document.body.clientWidth; var bodyheight = document.body.clientHeight; var divwidth = win.clientWidth; var divheight = win.clientHeight; var x, y; //控制left邊界 if ((x1 + event.clientX - x0) < 0)//超過左邊 { x = 0; } else if ((x1 + event.clientX - x0 + divwidth) > bodywidth) {//超過右邊 x = bodywidth - divwidth; } else { x = x1 + event.clientX - x0; } //控制top邊界 if (y1 + event.clientY - y0 < 0) {//超過頂邊 y = 0; } else if ((y1 + event.clientY - y0 + divheight) > bodyheight) {//超過底邊 y = bodyheight - divheight; } else { y = y1 + event.clientY - y0; } win.style.left = x; win.style.top = y; } } function stopDrag(obj) { if (moveable) { obj.releaseCapture(); moveable = false; } } function SetDivLayerAtCenter(objLayerName) { objLayer = document.getElementById(objLayerName); objLayer.style.top = document.body.clientHeight / 2 - objLayer.style.height.toLowerCase().replace('px', '') / 2; objLayer.style.left = document.body.clientWidth / 2 - objLayer.style.width.toLowerCase().replace('px', '') / 2; } function ShowDiv(objID) { SetDivLayerAtCenter(objID); document.getElementById(objID).style.display = ""; } function HideDiv(objID) { document.getElementById(objID).style.display = "none"; } </script> </head> <body> <a href="javascript:ShowDiv('SearchLay')" title="彈出層"> 彈出層</a> <div id="SearchLay" style="position: absolute; left: 15px; top: 69px; width: 225px; height: 225px; z-index: 1; display: none;"> <iframe style="position:absolute; z-index:-1; top:0; left:0; width: 100%; height:100%; filter:alpha(opacity=0);"></iframe> <div onmousedown="startDrag(this)" onmouseup="stopDrag(this);" onmousemove="drag(this)"> <table height="10" cellspacing="0" cellpadding="1" width="225" border="0"> <tr> <td width="100%" height="1" valign="top" class="SearchbgColor"> <table height="21" cellspacing="0" cellpadding="0" width="100%" border="0"> <tr> <td style=" background-color:Yellow;"> 我是彈出層頭 </td> <td align="center" width="50" style=" background-color:Yellow;"> <a href="javascript:HideDiv('SearchLay')">關閉彈出層</a> </td> </tr> </table> <table bgcolor="blue" width="225"><tr><td height="20"></td></tr></table> <table cellspacing="0" cellpadding="0" width="225" border="0" bgcolor="blue"> <tr> <td height="100"> 我是彈出層喔,親 </td> </tr> </table> </td> </tr> </table> </div> </div> </body> </html>