完美拖拽(简洁版)

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 <style>
 7 *{ margin:0; padding:0;}
 8 #move{ width:100px; height:100px; background-color:#333; cursor:move; position:absolute; left:0; top:0;}
 9 </style>
10 <script type="text/javascript" language="javascript">
11 //首先定义全局变量
12 var move=false;
13 var oldDiv,oldDivL,oldDivT,oldClientX,oldClientY;
14 window.onload=function(){
15     oldDiv=document.getElementById("move");
16     oldDiv.onmousedown=function (ev){
17         var ev=ev||event;
18         //IE系列浏览器需要函数来触发鼠标有效域
19         if(document.all){
20             oldDiv.setCapture();
21         }
22         move=true;
23         oldDivL=oldDiv.offsetLeft;
24         oldDivT=oldDiv.offsetTop;
25         oldClientX=ev.clientX;
26         oldClientY=ev.clientY;
27         document.onmousemove=function (ev){
28             var ev=ev||event;
29             if(move==true){
30                 oldDiv.style.left=ev.clientX-oldClientX+oldDivL+"px";
31                 oldDiv.style.top=ev.clientY-oldClientY+oldDivT+"px";
32                 oldDiv.style.cursor="move";
33             };
34             return false;    
35         }
36         document.onmouseup=function (ev){
37             var ev=ev||event;
38             //IE系列浏览器需要函数来解除鼠标有效
39             if(document.all){
40                 oldDiv.releaseCapture();
41             }
42             move=false;
43             document.onmousemove=null;
44             document.onmouseup=null;
45         }
46         //return false必须有,不然火狐浏览器拖动有BUG
47         return false;        
48     }
49 }
50 </script>
51 </head>
52 
53 <body>
54 <div id="move"></div>
55 </body>
56 </html>
posted @ 2012-06-25 15:35  胡淼  阅读(1021)  评论(0)    收藏  举报