实现代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>弹窗拖拽</title> <style> *{margin:0;padding:0;} .box{position: absolute;width: 400px;height: 300px;top:100px;left:100px;border:1px solid #001c67;background: #} .move{position: absolute;width: 100px;height: 100px;top:100px;left:150px;border:1px solid #000;} .move:hover{cursor: move;} .close{position: absolute;width: 30px;height: 30px;top:0px;right:0px;background:red;text-align: center;line-height: 30px;} </style> <script> window.onload=function(){ var oMove=document.getElementById('move'); // 拖曳 oMove.onmousedown=fnDown; // 关闭 var oClose=document.getElementById('close'); oClose.onclick=function(){ document.getElementById('box').style.display='none'; } } function fnDown(event){ event = event || window.event; var oDrag=document.getElementById('box'), // 光标按下时光标和面板之间的距离 disX=event.clientX-oDrag.offsetLeft, disY=event.clientY-oDrag.offsetTop; // 移动 document.onmousemove=function(event){ event = event || window.event; var l=event.clientX-disX, t=event.clientY-disY, // 最大left,top值 leftMax=(document.documentElement.clientWidth || document.body.clientWidth)-oDrag.offsetWidth, topMax=(document.documentElement.clientHeight || document.body.clientHeight)-oDrag.offsetHeight; if(l<0) l=0; if(l>leftMax) l=leftMax; if(t<0) t=0; if(t>topMax) t=topMax; oDrag.style.left=l+'px'; oDrag.style.top=t+'px'; } // 释放鼠标 document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; } } </script> </head> <body> <div> <div>拖拽区域</div> <div>X</div> </div> </body> </html>
主要注意几点:
1.event,IE兼容问题
2.点击鼠标时要先判断鼠标与面板之间的距离
3.要判断弹窗与浏览器整个区域的距离,不能让弹窗跑出浏览器外的区域
4.松开鼠标要解除事件绑定,不然会有bug