废话不多说,直接上代码。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box { width: 100px; height: 100px; background: repeating-linear-gradient(135deg, rgba(255, 255, 255, .5) 0, rgba(255, 255, 255, .5) 10px, rgba(0, 255, 0, .5) 10px, rgba(0, 255, 0, .5) 20px), repeating-linear-gradient(45deg, rgba(255, 255, 255, .5) 0, rgba(255, 255, 255, .5) 10px, rgba(0, 255, 0, .5) 10px, rgba(0, 255, 0, .5) 20px); } </style> </head> <body> <div class="box"></div> <script> let box = document.querySelector(".box"); box.onmousedown = function (event) { let { offsetX, offsetY } = event; document.onmousemove = function (event) { Object.assign(box.style, { position: "absolute", left: `${event.clientX - offsetX}px`, top: `${event.clientY - offsetY}px` }); } document.onmouseup = function () { document.onmousemove = null; } } </script> </body> </html>