Problema: tengo un elemento que necesito arrastrar con el cursor del mouse. Tengo un elemento contenedor (por ejemplo, 400x800) y necesito mover mi elemento secundario (2x2) al pasar el mouse sobre el contenedor. Lo hice con React, pero tengo algunos problemas de rendimiento. ¿Puede darme algún consejo sobre cómo puedo hacerlo con Pure CSS sin crear elementos div para cada px?
Algoritmo de arrastrar y soltar
Aquí está la implementación de arrastrar una bola:
ball.onmousedown = función (evento) {
let shiftX = event.clientX - ball.getBoundingClientRect().left; let shiftY = event.clientY - ball.getBoundingClientRect().top; ball.style.position = 'absolute'; ball.style.zIndex = 1000; document.body.append(ball); moveAt(event.pageX, event.pageY); // moves the ball at (pageX, pageY) coordinates // taking initial shifts into account function moveAt(pageX, pageY) { ball.style.left = pageX - shiftX + 'px'; ball.style.top = pageY - shiftY + 'px'; } function onMouseMove(event) { moveAt(event.pageX, event.pageY); } // move the ball on mousemove document.addEventListener('mousemove', onMouseMove); // drop the ball, remove unneeded handlers ball.onmouseup = function() { document.removeEventListener('mousemove', onMouseMove); ball.onmouseup = null; }; }; ball.ondragstart = function() { return false; };