本文实例为大家分享了js实现盒子拖拽动画的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
<!doctype html> <html lang= "zh-cn" > <head> <meta charset= "utf-8" > <title>document</title> <script src= "jquery.js" ></script> <style> * { margin: 0; padding: 0; } .wrap { width: 400px; height: 200px; border: 1px solid #ccc; border-right-color: red; position: absolute; top: 50%; left: 50%; margin-left: -200px; margin-top: -100px; box-sizing: border-box; } .wrap .head { height: 40px; padding-left: 4px; padding-right: 4px; background-color: #ccc; box-sizing: border-box; line-height: 40px; user-select: none; } .head:hover { cursor: move; } .head span { float: left; } #close { float: right; } #close:hover { cursor: pointer; } </style> </head> <body> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <p>tom</p> <div class= "wrap" > <div class= "head" > <span>试着拖拽我</span> <span id= "close" >【关闭】</span> </div> </div> <script> let wrap = document.queryselector( '.wrap' ); let close = document.getelementbyid( 'close' ); let head = document.queryselector( '.head' ); head.onmousedown = function (e) { // 获得鼠标在 head 中的坐标 let x = e.pagex - wrap.offsetleft; let y = e.pagey - wrap.offsettop; console.log(x, y); document.onmousemove = function (e) { let xx = e.pagex - x; let yy = e.pagey - y; // 设置边界限制 xx = xx < 0 ? 0 : xx; yy = yy < 0 ? 0 : yy; if (xx >= innerwidth - wrap.offsetwidth) { document.documentelement.scrollleft = 20; } else { document.documentelement.scrollleft = 0; } xx = xx > innerwidth - wrap.offsetwidth ? innerwidth-wrap.offsetwidth : xx; yy = yy > innerheight - wrap.offsetheight + document.documentelement.scrolltop ? innerheight - wrap.offsetheight + document.documentelement.scrolltop : yy; wrap.style.left = xx + 'px' ; wrap.style.top = yy + 'px' ; // 禁止x滚动轴 document.body.style.overflowx = 'hidden' ; wrap.style.marginleft = 0; wrap.style.margintop = 0; }; }; document.onmouseup = function () { document.onmousemove = null ; }; close.onclick = function () { wrap.style.display = 'none' ; }; </script> </body> </html> |
实现效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/cnkeysky/article/details/94299632