1.对于div块的position一定要设置,不然的话他根本就移不动,因为它默认的是static,并不能通过style.left来改变其位置。
2.在写onmousemove的时候我没有传进去ev,这样就会报event没有定义的错误。上面的那个时间对象是立即消失了吗?
3.如果给div上面加上onmousemove的时间,那么拖的时候如果鼠标移出去了就没有会出现问题。所以要把它改为document。发现改成了document后不论怎样都不会移出去。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1 { width: 100px; height: 100px; background: red; position: absolute; } </style> <script type="text/javascript"> window.onload = function () { var oDiv= document.getElementById('div1'); var disX = 0; var disY =0; oDiv.onmousedown = function (ev) { var oEvent = ev||event; disX = oEvent.clientX-oDiv.offsetLeft; disY = oEvent.clientY-oDiv.offsetTop; document.onmousemove = function (ev) { var oEvent = ev||event; var l = oEvent.clientX-disX; var t = oEvent.clientY-disY; if(l<0) { l = 0; } else if(l>document.documentElement.clientWidth-oDiv.offsetWidth) { l = document.documentElement.clientWidth-oDiv.offsetWidth; } if(t<0) { t=0; } else if(t>document.documentElement.clientHeight-oDiv.offsetHeight) { t = document.documentElement.clientHeight-oDiv.offsetHeight; } oDiv.style.left = l +'px'; oDiv.style.top =t +'px'; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; } } </script> </head> <body> <div id="div1"></div> </body> </html>