原生js实现div拖拽
十分简单的效果。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body{ height:1200px; background-color: azure; } #drag{ background-color: cornflowerblue; border: 1px solid black; position: absolute; width: 100px; height: 100px; } </style> </head> <body> <div id="drag"> </div> <script> //加入文字之后拖拽容易出现选中字后跳动bug var drag = document.getElementById("drag"), flag ; drag.addEventListener("mousedown",dragDiv,false); function dragDiv(e){ flag = true; var x=e.layerX||e.offsetX; var y=e.layerY||e.offsetY; document.addEventListener("mousemove",docMove,false); document.addEventListener("mouseup",function(){ flag = false; },false); function docMove(e){ if(flag){ e.preventDefault; var l =parseInt(drag.style.left); var t =parseInt(drag.style.top); drag.style.left = -x+e.pageX+"px"; drag.style.top = -y+e.pageY +"px"; console.log(drag); } } } </script> </body> </html>
posted on 2015-08-28 11:18 Leon·Vince 阅读(380) 评论(0) 编辑 收藏 举报