0
我期待的结果是红色方块顺利地跟随鼠标,而不是闪烁回原始位置。基本上,我想单击红色方块,将其拖动到某个区域,然后释放以获得新的位置。为什么它闪烁,我怎样才能实现简单的拖拽和跟随?JS偏移量X和偏移量Y在新位置和原始位置之间闪烁
HTML
<div style="height:500px; width:500px; background-color:#ccc;">
<div id="custom-front" style="width:100%; height:100%;">
<div id="custom-content" style="z-index:200; position:absolute; text-align:center; background-color:red; width:50px; height:50px;">
</div>
</div>
JS
window.onload = addListeners();
function addListeners(){
document.getElementById('custom-content').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp()
{
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e){
window.addEventListener('mousemove', divMove, true);
}
function divMove(e){
document.getElementById('custom-content').style.top = e.offsetY + 'px';
document.getElementById('custom-content').style.left = e.offsetX + 'px';
}
https://jsfiddle.net/703kc43a/1/