一、写在前面
如果我们想要实现拖拽的功能,必须要知道三个事件:
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> </body> <script> window.onload = function () { //获取drag元素 let drag = document.getElementById("drag") //当鼠标按下时 drag.onmousedown = function (e) { //做到浏览器兼容 e = e || window.event let diffX = e.clientX - drag.offsetLeft let diffY = e.clientY - drag.offsetTop //当拉着box移动时 document.onmousemove = function (e) { // 浏览器兼容 e = e || window.event let left = e.clientX - diffX let top = e.clientY - diffY 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) { this.onmousemove = null this.onmouseup = null } } } </script> </html>