首页 > 代码库 > 一个可以拖拽的div

一个可以拖拽的div

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <style>
 7         #box{
 8             margin:100px;
 9             width: 200px;
10             height: 200px;
11             background-color: green;
12         }
13         #box:hover{
14             cursor: pointer;
15         }
16     </style>
17 </head>
18 <body>
19 <div>
20     <div id="box"></div>
21     </div>
22     <script>
23         var $box=document.getElementById(box);
24         var $x,$y;
25         $box.onmousedown=function(e){
26             $x=parseInt(e.pageX-parseInt($box.offsetLeft));
27             $y=parseInt(e.pageY-parseInt($box.offsetTop));
28             $box.onmousemove=function(e){
29                 $box.style.marginLeft=e.pageX-$x+px;
30                 $box.style.marginTop=e.pageY-$y+px;
31             }
32         }
33         window.onmouseup=function(){
34             
35             $box.onmousemove=null;
36         }
37     </script>
38 </body>
39 </html>

一个可以拖拽的div