拖拽时间

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         *{
 8             margin: 0;
 9             padding:0;
10         }
11         html,body{
12             width: 100%;
13             height: 100%;
14         }
15         #box{
16             width: 100%;
17             height: 100%;
18             position: relative;
19         }
20         #dragBox{
21             width: 200px;
22             height: 100px;
23             background: #ff0000;
24             position: absolute;
25             left: 0;
26             top:0;
27         }
28     </style>
29 </head>
30 <body>
31 <div id="box">
32     <div id="dragBox"></div>
33 </div>
34 <script>
35     var box=document.getElementById('box');
36     var dragBox=document.getElementById('dragBox');
37     var mouseOffsetX=0;
38     var mouseOffsetY=0;
39     var isDragging=false;//设置是否可以拖动
40     dragBox.addEventListener('mousedown', function(e){
41         var evt=e||window.event;
42         mouseOffsetX= evt.clientX-dragBox.offsetLeft;
43         mouseOffsetY= evt.clientY-dragBox.offsetTop;
44         isDragging=true;
45     });
46    dragBox.onmousemove=function(e){
47        var evt=e||window.event;
48        var mouseX= evt.clientX;
49        var mouseY=evt.clientY;
50 
51        var moveX=0;
52        var moveY=0;
53 
54        if(isDragging===true){
55            moveX=mouseX-mouseOffsetX;
56            moveY=mouseY-mouseOffsetY;
57            //限定范围
58            var pageW=box.clientWidth;
59            var pageH=box.clientHeight;
60 
61            var objW=dragBox.offsetWidth;
62            var objH=dragBox.offsetHeight;
63 
64            var maxX=pageW-objW;
65            var maxY=pageH-objH;
66 
67            moveX=Math.min(maxX,Math.max(0,moveX));
68            moveY=Math.min(maxY,Math.max(0,moveY));
69 
70            dragBox.style.left=moveX+'px';
71            dragBox.style.top=moveY+'px';
72        }
73    };
74     dragBox.onmouseup=function(){
75         isDragging=false;
76     }
77 
78 </script>
79 </body>
80 </html>

 

posted @ 2016-08-16 23:59  凉城丶旧梦  阅读(190)  评论(0编辑  收藏  举报