<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <title>Document</title> <style> #box{width: 200px; height: 200px; background-color: #ccc;position: absolute; left: 400px; top: 200px;} </style> </head> <body> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <p>asdfasdf</p> <div id="box"></div> <script> var oDiv = document.getElementById('box'); oDiv.onmousedown = function(ev){ var oEvent = ev || event; //xy - 算鼠标距离元素的位置 var x = oEvent.clientX - oDiv.getBoundingClientRect().left, y = oEvent.clientY - oDiv.getBoundingClientRect().top; document.onmousemove = function(ev){ var oEvent = ev || event; //物体要移动的位置 var l = oEvent.clientX - x, t = oEvent.clientY - y; // console.log(l); if(l<=0) l=0; if(t<=0) t=0; if(l>=document.documentElement.clientWidth - oDiv.offsetWidth) l=document.documentElement.clientWidth - oDiv.offsetWidth; if(t>=document.documentElement.clientHeight - oDiv.offsetHeight) t=document.documentElement.clientHeight - oDiv.offsetHeight; oDiv.style.left = l + 'px'; oDiv.style.top = t + 'px'; } oDiv.onmouseup = function(){ if(oDiv.releaseCapture) oDiv.releaseCapture(); document.onmousemove = null; } if(oDiv.setCapture) oDiv.setCapture(); return false; } </script> </body> </html>