<!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; } html, body { background-color: aqua; } #container { position: absolute; top: 150px; left: 150px; background-color: yellow; width: 500px; height: 500px; } #drag { width: 300px; height: 300px; background: red; cursor: pointer; position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div id="container"> <div id="drag"></div> </div> <script> window.onload = function () { //获取drag元素 let drag = document.getElementById("drag"); // 获取画布元素 let container = document.getElementById("container"); //当鼠标按下时 drag.onmousedown = function (e) { // drag.offsetLeft/offsetTop 是自身相对于父容器的左和上偏移量 console.log("offsetLeft", drag.offsetLeft); console.log("offsetTop", drag.offsetTop); //做到浏览器兼容 e = e || window.event; console.log("onmousedown", e); // console.log("window.event", window.event); // 计算鼠标点击位置相对于元素左上角的左边和上边距离 // e.clientX/e.pageX 是点击位置相对于页面左上角的偏移量 // e.offsetLeft/e.offsetTop 是点击位置相对于点击元素本身左上角偏移量 // diffX = 点击时相对页面的左侧距离-元素本身的偏移量 let diffX = e.clientX - drag.offsetLeft; let diffY = e.clientY - drag.offsetTop; console.log("diffX", diffX); console.log("diffY", diffY); //当拉着box移动时 document.onmousemove = function (e) { // 浏览器兼容 e = e || window.event; console.log("onmousemove", e); // 元素的 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 > container.clientWidth - drag.offsetWidth) { left = container.clientWidth - drag.offsetWidth; } if (top < 0) { top = 0; } else if (top > container.clientHeight - drag.offsetHeight) { top = container.clientHeight - 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,log,top,元素,js,drag,拖拽,left From: https://www.cnblogs.com/beileixinqing/p/16890033.html