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/