码迷,mamicode.com
首页 > Web开发 > 详细

JS事件中级 --- 拖拽

时间:2015-06-10 11:43:05      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

http://bbs.zhinengshe.com/thread-1200-1-1.html

 

要求:实现div块的拖拽

原理:拖拽过程中鼠标点和div块的相对位置保持不变。

 

需要理解三点:

1. 为什么要把onmousemove,onmouseup加在document上面 ?

2. onmouseup要怎么使用 ?

3. 如何防止div块跑出边界 ?

 

技术分享
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         #div1 {
 8             width: 200px;
 9             height: 200px;
10             background-color: red;
11             position: absolute;
12         }
13     </style>
14     <script>
15         window.onload = function () {
16             var oDiv = document.getElementById("div1");
17 
18             var disX = 0;
19             var disY = 0;
20 
21             oDiv.onmousedown = function (event) {
22                 disX = event.clientX - oDiv.offsetLeft;
23                 disY = event.clientY - oDiv.offsetTop;
24 
25                 document.onmousemove = function (event) {
26 
27                     var divLeft = event.clientX - disX;
28                     var divTop = event.clientY - disY;
29 
30                     if (divLeft < 0) divLeft = 0;
31                     if (divLeft > document.documentElement.clientWidth-oDiv.offsetWidth) {
32                         divLeft = document.documentElement.clientWidth-oDiv.offsetWidth;
33                     }
34                     if (divTop < 0) divTop = 0;
35                     if (divTop > document.documentElement.clientHeight - oDiv.offsetHeight) {
36                         divTop = document.documentElement.clientHeight - oDiv.offsetHeight;
37                     }
38 
39                     oDiv.style.left = divLeft + "px";
40                     oDiv.style.top = divTop + "px";
41                 };
42                 document.onmouseup = function () {
43                     document.onmousemove = null;
44                     document.onmouseup = null;
45                 }
46             };
47         }
48     </script>
49 </head>
50 <body>
51     <div id="div1"></div>
52 </body>
53 </html>
View Code

 

运行效果:【点击这里】

 

JS事件中级 --- 拖拽

标签:

原文地址:http://www.cnblogs.com/linxd/p/4565311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!