Estoy tratando de arrastrar una caja con mi mouse. Cuando el mouse hace clic y se mueve, la caja se moverá con el mouse. Cuando el mouse rebota, deja de moverse. Así es como lo hago.
<html> <head> <style> div{ width: 100px; height: 100px; background-color: pink; } </style> </head> <body> <div> </div> <script> var div = document.querySelector('div') div.addEventListener('mousedown', function(e){ x = e.pageX - div.offsetLeft; y = e.pageY - div.offsetTop; div.addEventListener('mousemove', move) // when mouse move, change the position of div function move(e) { div.style.left = e.pageX-x + 'px'; // not working div.style.top = e.pageY-y + 'px'; // not working } div.addEventListener('mouseup', function(e){ div.removeEventListener('mousemove', move) }) }) </script> </body> </html> Puedo obtener la nueva posición (izquierda y derecha) del cuadro por e.pageX-x + 'px' . Pero div.style.left = e.pageX-x + 'px' parece no funcionar. Alguien sabe cual es el problema?
Debe agregar la position: absolute; estilo al elemento div que está tratando de arrastrar/soltar.
Echar un vistazo:
<html> <head> <style> div{ width: 100px; height: 100px; position: absolute; background-color: pink; } </style> </head> <body> <div> </div> <script> var div = document.querySelector('div') div.addEventListener('mousedown', function(e){ x = e.pageX - div.offsetLeft; y = e.pageY - div.offsetTop; div.addEventListener('mousemove', move) // when mouse move, change the position of div function move(e) { div.style.left = e.pageX-x + 'px'; // not working div.style.top = e.pageY-y + 'px'; // not working } div.addEventListener('mouseup', function(e){ div.removeEventListener('mousemove', move) }) }) </script> </body> </html>