元素的移动

我的想法:

1.首先给移动的元素一个绝对定位,position: absolute, 通过top和left来实现元素的移动。

2. 基本过程:(1)当鼠标的左键按下去时,给元素添加onmousemove, onmouseleave(鼠标不在元素上时, 移除onmousemove事件),

          onmouseup(一个移动的完整操作)事件,并触发该元素的 onmousemove 事件。

      (2) 记录鼠标的移动前和移动后的水平和垂直位置,他们的差值就是元素在水平和垂直的移动距离 ,再减去鼠标在移动元素上的相对的水平和垂直位置

          ,最后得到元素移动的目的地(位置)。

  1 <!DOCTYPE html>
  2 <html>
  3 
  4 <head>
  5 
  6 <meta charset="UTF-8">
  7 
  8 <title></title>
  9 
 10 <style>
 11 
 12 *{
 13 
 14 padding: 0px;
 15 
 16 margin: 0px;
 17 
 18 }
 19 
 20 body{
 21 
 22  100%;
 23 
 24 height: 100%;
 25 
 26 background-color: #204D74;
 27 
 28 }
 29 
 30 div{
 31 
 32 position: absolute;
 33 
 34  400px;
 35 
 36 height: 100px;
 37 
 38 background-color: #008000;
 39 
 40 cursor: pointer;
 41 
 42 }
 43 
 44 </style>
 45 
 46 </head>
 47 
 48 <body>
 49 
 50 <div onmousedown="startDrop(event)"></div>
 51 
 52 </body>
 53 
 54 <script>
 55 
 56 var mouseCurrentX;
 57 
 58 var mouseCurrentY;
 59 
 60 var moveX = 0;
 61 
 62 var moveY = 0;
 63 
 64 function startDrop(e) {
 65 
 66 mouseCurrentX = e.clientX;
 67 
 68 mouseCurrentY = e.clientY;
 69 
 70 console.log('开始拖动');
 71 
 72 if (e.target.addEventListener) {
 73 
 74 e.target.addEventListener('mousemove', mouseMove, false);
 75 
 76 e.target.addEventListener('mouseup', stopMove, false);
 77 
 78 e.target.addEventListener('mouseleave', stopMove, false);
 79 
 80 }else if (attachEvent){
 81 
 82 e.target.attachEvent('onmousemove', mouseMove, false);
 83 
 84 e.target.attachEvent('onmouseup', stopMove, false);
 85 
 86 }
 87 
 88 }
 89 
 90 function mouseMove(e) {
 91 
 92 console.log('正在移动');
 93 
 94 moveX = e.clientX - mouseCurrentX;
 95 
 96 moveY = e.clientY - mouseCurrentY;
 97 
 98 var x = e.clientX - e.offsetX + moveX;
 99 
100 var y = e.clientY - e.offsetY + moveY;
101 
102 e.target.style.top = y + 'px';
103 
104 e.target.style.left = x + 'px';
105 
106 mouseCurrentX = e.clientX;
107 
108 mouseCurrentY = e.clientY;
109 
110 console.log('元素当前的坐标为: ' + x + ',' + y);
111 
112 }
113 
114 function stopMove(e){
115 
116 console.log('结束移动');
117 
118 e.target.removeEventListener('mousemove', mouseMove);
119 
120 }
121 
122 </script>
123 
124 </html>

 ***********************************************************

 2018-08-10

但感觉还有写小毛病,欢迎指点(致电) 。

原文地址:https://www.cnblogs.com/hello-dummy/p/9454809.html