跟随鼠标按下移动的div

tech2026-04-19  0

<!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> div { position: relative; left: 100px; top: 10px; width: 300px; height: 300px; background-color: green; } </style> </head> <body> <div></div> <script> var div = document.querySelector('div'); div.addEventListener('mousedown', function (e) { var borderinx = e.pageX - div.offsetLeft; var borderiny = e.pageY - div.offsetTop; document.addEventListener('mousemove', move); function move(e) { // 切记加px div.style.left = e.pageX - borderinx + 'px'; div.style.top = e.pageY - borderiny + 'px'; } document.onmouseup = function () { // document.onmousemove = null; // 解绑事件的对象不要弄错了 document.removeEventListener('mousemove', move); } }); </script> </body> </html>

遇到两个问题,都比较有意义 **

1.pagex,offsetleft等值都是数值,必须要添加px才起作用2.解绑事件的对象不要弄错了

**

最新回复(0)