<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>拖拽</title> <style type="text/css"> #div1 {width: 100px; height: 100px; background: red; position: absolute;} #img1 { position: absolute;} </style> </head> <body> <div id="div1"></div> <img src="http://cz.xcabc.com/Img/201704/24/20170424013138348.jpg" id="img1" /> <script type="text/javascript"> window.onload = function() { var oDiv = document.getElementById('div1'); var oImg = document.getElementById('img1'); drag(oImg); drag(oDiv); function drag(obj) { obj.onmousedown = function(ev) { var ev = ev || event; var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop; document.onmousemove = function(ev) { var ev = ev || event; obj.style.left = ev.clientX - disX + 'px'; obj.style.top = ev.clientY - disY + 'px'; } document.onmouseup = function() { document.onmousemove = document.onmouseup = null; } return false; } } } </script> </body> </html> 提示:你可以先修改部分代码再运行。 转载请注明:有爱前端 » 拖拽js 喜欢 (0)or分享 (0)