JS弹出可拖拽可关闭的div层完整实例
本文实例讲述了JS弹出可拖拽可关闭的div层完整实现方法。分享给大家供大家参考。具体实现方法如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>JS弹出可拖拽可关闭的div层</title>
<style>
html,body{height:100%;overflow:hidden;}
body,div,h2{margin:0;padding:0;}
body{font:12px/1.5Tahoma;}
center{padding-top:10px;}
button{cursor:pointer;}
#win{position:absolute;top:50%;left:50%;width:400px;height:200px;background:#fff;border:4pxsolid#f90;margin:-102px00-202px;display:none;}
h2{font-size:12px;height:18px;text-align:right;background:#FC0;border-bottom:3pxsolid#f90;padding:5px;cursor:move;}
h2span{color:#f90;cursor:pointer;background:#fff;border:1pxsolid#f90;padding:02px;}
</style>
<script>
window.onload=function()
{
varoWin=document.getElementById("win");
varoBtn=document.getElementsByTagName("button")[0];
varoClose=document.getElementById("close");
varoH2=oWin.getElementsByTagName("h2")[0];
varbDrag=false;
vardisX=disY=0;
oBtn.onclick=function()
{
oWin.style.display="block"
};
oClose.onclick=function()
{
oWin.style.display="none"
};
oClose.onmousedown=function(event)
{
(event||window.event).cancelBubble=true;
};
oH2.onmousedown=function(event)
{
varevent=event||window.event;
bDrag=true;
disX=event.clientX-oWin.offsetLeft;
disY=event.clientY-oWin.offsetTop;
this.setCapture&&this.setCapture();
returnfalse
};
document.onmousemove=function(event)
{
if(!bDrag)return;
varevent=event||window.event;
variL=event.clientX-disX;
variT=event.clientY-disY;
varmaxL=document.documentElement.clientWidth-oWin.offsetWidth;
varmaxT=document.documentElement.clientHeight-oWin.offsetHeight;
iL=iL<0?0:iL;
iL=iL>maxL?maxL:iL;
iT=iT<0?0:iT;
iT=iT>maxT?maxT:iT;
oWin.style.marginTop=oWin.style.marginLeft=0;
oWin.style.left=iL+"px";
oWin.style.top=iT+"px";
returnfalse
};
document.onmouseup=window.onblur=oH2.onlosecapture=function()
{
bDrag=false;
oH2.releaseCapture&&oH2.releaseCapture();
};
};
</script>
</head>
<body>
<divid="win"><h2><spanid="close">×</span></h2></div> <center><button>弹出层</button></center> </body> </html>