<style>
.drag {
position: absolute;
}
</style>
<div class="drag">drag</div>
<script>
let dragDiv = document.querySelector('.drag');
let startX = 0;
let startY = 0;
dragDiv.addEventListener('mousedown', dragStart);
function dragStart(e) {
e.preventDefault();
//記錄點擊相對被點擊物件的座標
startX = e.clientX - dragDiv.offsetLeft;
startY = e.clientY - dragDiv.offsetTop;
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
}
function move(e) {
//計算出拖曳物件最左上角座標
x = e.clientX - startX;
y = e.clientY - startY;
dragDiv.style.left = x + 'px';
dragDiv.style.top = y + 'px';
}
function stop() {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop)
}
</script>
沒有留言:
張貼留言