用纯css映射到元素位置



问题:我有一个需要用鼠标拖动的元素。我有容器元素(例如400x800),我需要移动我的子元素(2x2)时,悬停在容器上。我是用React做的,但我遇到了一些性能问题。请给我一些建议,我怎么能做到这一点与纯CSS没有创建div元素每px?

拖放算法

基本的拖放算法如下:

<编辑>1。按下鼠标-准备移动的元素,如果需要(可能创建它的克隆,添加一个类或其他)。<编辑>2。然后在鼠标上移动,通过改变位置:绝对的左/上移动它。<编辑>

3。在鼠标上-执行与完成拖放相关的所有操作。下面是拖动球的实现:

球。Onmousedown = function(event) {

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;
};