JS事件中级 --- 拖拽

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

运行效果:【点击这里】

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