模拟拖拽-小火柴博客

学习他人的博客写出来的东西,记录一下。

原博客写的比我好多了源博客:小火柴的蓝色理想 - javascript动画系列第一篇——模拟拖拽

模拟拖拽

 

 1         var Div = document.getElementById('Div');
 2 
 3         Div.onmousedown = function(e){
 4             e = e || event;
 5             // 获取当前元素距离父级的X轴和Y轴的距离
 6             var x0 = this.offsetLeft;
 7             var y0 = this.offsetTop;
 8             // 获取当前鼠标距离视口左上角的X轴和Y轴的距离
 9             var x1 = e.clientX;
10             var y1 = e.clientY;
11 
12              Div.onmousemove = function(e){
13             // 【1】document.onmousemove = function(e){
14                 e = e || event;
15                 // 获取当前鼠标距离距离视口左上角的X轴和Y轴的距离
16                 var x2 = e.clientX;
17                 var y2 = e.clientY;
18                 // 计算元素现在所在的位置
19                 var x = x0 + (x2 - x1);
20                 var y = y0 + (y2 - y1);
21                 // 赋值
22                 Div.style.left = x + 'px';
23                 Div.style.top = y + 'px';
24             }
25 
26              Div.onmouseup = function(e){
27             //【1】 document.onmouseup = function(e){
28 
29                 // 当鼠标抬起时,拖拽结束
30                   Div.onmousemove = null;
31                 // 【1】document.onmousemove = null;
32             }
33         }

  此时的代码有个小问题,就是在鼠标移动过快时,图片会不动。这是因为鼠标拖动的太快,比onmousemove事件的触发间隔还要快时,鼠标就会从元素上离开。这样就停止了元素的拖拽过程
解决这个小bug需要把onmouseover和onmouseup事件添加到document上便可以解决(将【1】处的代码将它
上一行的代码替换)

不要在该奋斗的年纪而选择了安逸
原文地址:https://www.cnblogs.com/qqandfqr/p/5899569.html