<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Drag</title>
<style>
.drag {
border: 1px solid red;
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="drag"></div>
<script>
let dragging = false;
let position = null;
const dragEle = document.querySelector('.drag');
dragEle.addEventListener("mousedown", e => {
dragging = true;
position = [e.clientX, e.clientY];
});
document.addEventListener("mousemove", e => {
if (!dragging) return;
const x = e.clientX;
const y = e.clientY;
const moveX = x - position[0];
const moveY = y - position[1];
const left = parseInt(dragEle.style.left || 0);
const top = parseInt(dragEle.style.top || 0);
dragEle.style.left = left + moveX + 'px';
dragEle.style.top = top + moveY + 'px';
position = [x, y];
});
document.addEventListener('mouseup', e => {
dragging = false;
})
</script>
</body>
</html>
网友评论