带框拖拽

运行效果图:[点击这里]

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         * {
 8             border: 0px;
 9             margin: 0px;
10         }
11         #div1 {
12             width: 100px;
13             height: 100px;
14             background-color: red;
15             position: absolute;
16         }
17         .box {
18             border: 1px dashed black;
19             position: absolute;
20         }
21     </style>
22     <script>
23         window.onload = function () {
24             var oDiv = document.getElementById("div1");
25 
26             oDiv.onmousedown = function (event) {
27                 var disX = event.clientX - oDiv.offsetLeft;
28                 var disY = event.clientY - oDiv.offsetTop;
29 
30                 var oBox = document.createElement("div");
31                 oBox.className = "box";
32                 oBox.style.width = oDiv.offsetWidth + "px";
33                 oBox.style.height = oDiv.offsetHeight + "px";
34                 oBox.style.left = oDiv.offsetLeft-1 + "px";
35                 oBox.style.top = oDiv.offsetTop-1 + "px";
36                 document.body.appendChild(oBox);
37 
38                 document.onmousemove = function (event) {
39                     var divLeft = event.clientX - disX;
40                     var divTop = event.clientY - disY;
41 
42                     if (divLeft < 0) divLeft = 0;
43                     if (divLeft > document.documentElement.clientWidth - oDiv.offsetWidth) {
44                         divLeft = document.documentElement.clientWidth - oDiv.offsetWidth;
45                     }
46                     if (divTop < 0) divTop = 0;
47                     if (divTop > document.documentElement.clientHeight - oDiv.offsetHeight) {
48                         divTop = document.documentElement.clientHeight - oDiv.offsetHeight;
49                     }
50 
51                     oBox.style.top = divTop + "px";
52                     oBox.style.left = divLeft + "px";
53                 };
54 
55                 document.onmouseup = function () {
56                     oDiv.style.top = oBox.style.top;
57                     oDiv.style.left = oBox.style.left;
58                     document.body.removeChild(oBox);
59 
60                     document.onmousemove = null;
61                     document.onmouseup = null;
62                 };
63             };
64         };
65     </script>
66 </head>
67 <body>
68     <div id="div1"></div>
69 </body>
70 </html>
View Code
原文地址:https://www.cnblogs.com/linxd/p/4566499.html