javascript6鼠標拖拽圖片

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6         <style> #div1{width: 100px; height: 100px; background-color: red; position: absolute;}</style>
 7         <script>
 8                 
 9             window.onload=function(){
10             var oDiv=document.getElementById("div1");
11             oDiv.onmousedown=function(ev){
12                 var e=ev||window.event;
13                 var offsetX=e.clientX-oDiv.offsetLeft;//獲取鼠標離當前拖拽圖片的左上角的距離
14                 var offsetY=e.clientY-oDiv.offsetTop;
15                 document.onmousemove=function(ev){
16                     var e=ev||window.event;
17                     oDiv.style.left=e.clientX-offsetX+"px";//獲取圖片偏移距離
18                     oDiv.style.top=e.clientY-offsetY+"px";
19                 }
20             }
21             document.onmouseup=function(){
22                 document.onmousemove=null;//清除鼠標移動
23             }
24             }
25             
26         </script>
27     </head>
28     <body>
29         <div id="div1"></div>
30     </body>
31 </html>
相關文章
相關標籤/搜索