为你而来

javascript:用mousedown和mouseup实现的鼠标拖动事件

 1 <html>
 2 <head>
 3 <title>1</title>
 4 <style type='text/css'>
 5 #box{
 6     width:100px;
 7     height:100px;
 8     border:dashed 1px green;
 9     position:absolute;
10     left:300px;
11     top:300px;
12 }
13 </style>
14 </head>
15 <body>
16 <div id='box' onmousedown="fun1();" onmouseup="fun();">
17 </div>
18 <script language='javascript'>
19     var flag=false;
20     var x,y;
21     var obj=document.getElementById('box');
22     function fun1(){
23         flag=true;
24         x=event.offsetX;
25         y=event.offsetY;
26     }
27     function fun(){
28         obj.style.left=(obj.offsetLeft+(event.offsetX-x))+'px';
29         obj.style.top=(obj.offsetTop+(event.offsetY-y))+'px';
30         flag=false;
31     }
32 
33 </script>
34 
35 </body>
36 </html>

 

posted on 2012-06-07 17:54  为你而来  阅读(2261)  评论(0编辑  收藏  举报

导航