<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> *{margin:0; padding:0;} #panal{width:200px; height:200px; position:absolute; background:#eee; display:none; left:50%; top:50%; margin-left:-100px; margin-top:-100px; } #hand{background:deepskyblue; color:white; height:50px; cursor:pointer;} #close{display:block; width:40px; height:30px; background-color:firebrick; cursor:pointer; color:white; float:right; font-size:10px; text-align:center; line-height:30px;} </style> <script> window.onload=function(){ var oPanal=document.getElementById('panal'); //弹框面板 var oClose=document.getElementById('close'); //关闭按钮 var oShow=document.getElementById('show'); //弹出按钮 oShow.onclick=function(){ // 点击显示弹框 oPanal.style.display='block'; } oClose.onclick=function(){ //点击关闭弹窗 oPanal.style.display='none'; } var oHand=document.getElementById('hand'); oHand.onmousedown=function(event){ //鼠标按下 event=event||window.event; /*由于起初定位采用了margin,此时重新进行定位*/ oPanal.style.left=oPanal.offsetLeft+'px'; oPanal.style.top=oPanal.offsetTop+'px'; oPanal.style.margin=0; //清除margin var oPosx=event.clientX-oPanal.offsetLeft; // 获取鼠标坐标到弹框左边的距离 var oPosy=event.clientY-oPanal.offsetTop; //上边 oHand.onmouseup=function(){ // 鼠标抬起取消拖拽 oHand.onmousemove=null; } oHand.onmouseout=function(){ //鼠标移出hand区域取消拖拽 oHand.onmousemove=null; } oHand.onmousemove=function(event){ // 鼠标在hand上移动触发 event=event||window.event; var pLeft=event.clientX-oPosx; //弹框的左边距 var pTop=event.clientY-oPosy; //上边距 /*限制弹框的移动距离*/ var winWidth=document.documentElement.clientWidth || document.body.clientWidth; //浏览器的窗口长度 var winHeight=document.documentElement.clientHeight || document.body.clientHeight; var maxLeft=winWidth-oPanal.offsetWidth; //最大的左边距 var maxTop=winHeight-oPanal.offsetHeight; //上边距 if(pLeft<0){ pLeft=0; }else if(pLeft>maxLeft){ pLeft=maxLeft; } if(pTop<0){ pTop=0; }else if(pTop>maxTop){ pTop=maxTop; } oPanal.style.left=pLeft+'px'; oPanal.style.top=pTop+'px'; } } } </script> </head> <body> <div id="panal"> <h2 id="hand">点击拖拽<span id="close" title="点我关闭弹窗">关闭</span></h2> </div> <a href="javascript:;" id="show">拖拽窗口</a> </body> </html>
代码是参考的Amy老师的视频,然后写出来的,老师的课程都不错,Amy思路清晰细致