- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title></title>
- <style>
- div{
- margin-top: 10px;
- width: 200px;
- height: 150px;
- background: #dadada;
- position: absolute;
- cursor:move;
- }
- </style>
- </head>
- <body>
- <div id="div" ></div>
- <script>
- var drag=false;
- var x, y,movex,movey;
- var movediv =document.getElementById('div');
- movediv.onmousedown=function(){
- drag=false;
- x = window.event.clientX; /*当前鼠标坐标*/
- y =window.event.clientY;
- movex = movediv.offsetLeft; /*当前元素坐标*/
- movey =movediv.offsetTop
- }
- document.onmousemove=function(){
- if(drag) return false;
- movediv.style.top= movey + window.event.clientY -y +'px';
- movediv.style.left= movex + window.event.clientX -x +'px';
- }
- document.onmouseup=function(){drag=true}
- </script>
- </body>
- </html>
来源: http://www.phpxs.com/code/1003965/