当鼠标拖拽的很快时,光标会走出方块,所以把事件注册在了方块的父节点上,
如有疑问请参照:http://blog.csdn.net/a9529lty/article/details/2708171
使用了 IntelliJ IDEA 的html编辑器,推荐大家使用
多说无益,代码如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>拖拽div</title> </head> <body> <div id="background" style="width:800px;height:450px;background-color:lightblue"> <div id="drag_div" style="width:50px;height:50px;background-color:red"></div> </div> <script> var background = document.querySelector("#background"); var div1 = background.querySelector("#drag_div"); var dragable = false; div1.onmousedown = function(event){ var thisP = {X : this.offsetLeft, Y : this.offsetTop}; var eventP = {X : event.pageX, Y : event.pageY}; dragable = true; var this_outer = this; this.parentNode.onmouseup = function(event){ dragable = false; this.onmouseup = null; this.onmousemove = null; } this.parentNode.onmousemove = function(event){ if(dragable){ this_outer.style.position = "absolute"; var currentP = {X : event.pageX, Y : event.pageY}; this_outer.style.left = currentP.X - eventP.X + thisP.X + "px"; this_outer.style.top = currentP.Y - eventP.Y + thisP.Y + "px"; } } } </script> </body> </html>
运行结果如下,童鞋们可以把上面的代码拷贝到文本文档里另存为html格式, 然后用浏览器打开就可以看到结果了 !