In www.cnblogs.com/psxiao/p/11… I got a question: why do I use top and left to implement, and who is better than transform? Then I made a version with Transform
<! 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, Word-wrap: break-word! Important; "> < span style> < span style>. position: absolute; line-height: 100px; text-align: center; user-select:none; } </style> </head> <body> <div> <div class="drag" style="left:0; top:0; width:100px; Height: 100 px "> hold drag < / div > < / div > < script > / / access to DOM elements let dragDiv = document. The getElementsByClassName (" drag") [0]; Let putDown = function (event) {dragdiv.style. cursor = "pointer"; let offsetX = dragDiv.getBoundingClientRect().left; / / get the current x axes from the let offsetY = dragDiv. GetBoundingClientRect (). The top; // let innerX = event. Clientx-offsetx; Let innerY = event. ClientY - offsetY; Document. onMousemove = function (event) {var X = event. Clientx-innerx; var Y = event.clientY - innerY; dragDiv.style.transform = `translate(${X}px,${Y}px)`; Dragdiv.style. transform = 'translate(${X}px,${Y}px)'; } if (Y <= 0) { Y=0 dragDiv.style.transform = `translate(${X}px,${Y}px)`; } if (X >= window.innerWidth - parseInt(dragDiv.style.width)) { X = window.innerWidth - parseInt(dragDiv.style.width); dragDiv.style.transform = `translate(${X}px,${Y}px)`; } if (Y >= window.innerHeight - parseInt(dragDiv.style.height)) { Y = window.innerHeight - parseInt(dragDiv.style.height); dragDiv.style.transform = `translate(${X}px,${Y}px)`; }} // When the mouse is up, Document.onmouseup = function () {document.onmousemove = null; document.onmouseup = null; }} // Bind the mouse button event dragdiv. addEventListener("mousedown", putDown, false); </script> </body> </html>Copy the code
let offsetX = dragDiv.getBoundingClientRect().left; / / get the current x axes from the let offsetY = dragDiv. GetBoundingClientRect (). The top; When I change it to transform, each click will return to top: 0, left: 0, so remember to get the X and Y values of the transform, and the getBoundingClientRect () killer will come back to me