概述
js 实现拖拽,主要使用元素的 onm ousedown、onmousemove、onmouseup 三个事件实现。
1、onmousedown:
鼠标按下事件2、onmousemove:
鼠标移动事件3、onmouseup:
鼠标抬起事件
实现思路
- 我们当左键点击时,需要记录当前的鼠标点击位置相对于该元素左上角的x,y坐标,这里我们使用diffX和diffY来表示
- 然后我们移动时需要不断计算当前元素距离浏览器左边和上边的距离;
- 同时给元素进行赋值;
- 当鼠标抬起时,取消鼠标移动事件和鼠标抬起事件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0px; padding: 0px; } #drag { width: 200px; height: 200px; background: red; cursor: pointer; position: absolute; } </style> </head> <body> <div id="drag"></div> <script> window.onload = function () { //获取drag元素 let drag = document.getElementById("drag"); //当鼠标按下时 drag.onmousedown = function (e) { console.log("onmousedown", e); console.log("offsetLeft", drag.offsetLeft); console.log("offsetTop", drag.offsetTop); //做到浏览器兼容 e = e || window.event; // 计算鼠标点击位置相对于元素左上角的左边和上边距离 let diffX = e.clientX - drag.offsetLeft; let diffY = e.clientY - drag.offsetTop; //当拉着box移动时 document.onmousemove = function (e) { console.log("onmousemove", e); // 浏览器兼容 e = e || window.event; // 元素的 clientX 和 clientY 默认是以元素左上角位置来计算的,这里需要向左向上同时减去鼠标点击的位置差,从而可以保证鼠标始终显示在拖拽元素时的位置 let left = e.clientX - diffX; let top = e.clientY - diffY; console.log("left", left); console.log("top", top); // 边界处理,防止超出各个边 if (left < 0) { left = 0; } else if (left > window.innerWidth - drag.offsetWidth) { left = window.innerWidth - drag.offsetWidth; } if (top < 0) { top = 0; } else if (top > window.innerHeight - drag.offsetHeight) { top = window.innerHeight - drag.offsetHeight; } // 实时给元素定位赋值 drag.style.left = left + "px"; drag.style.top = top + "px"; }; // 当鼠标抬起时 document.onmouseup = function (e) { console.log("onmouseup", e); this.onmousemove = null; this.onmouseup = null; }; }; }; </script> </body> </html>标签:console,鼠标,top,元素,window,js,drag,拖拽,left From: https://www.cnblogs.com/beileixinqing/p/16842917.html