实现一个可拖拽的div
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实现可拖拽的div</title>
<style>
body {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="div"></div>
</body>
<script>
/*
注意事项:
1.clientX是没有单位的,left是有单位的
2.mousemove事件放到document上,而不是放到div上,是为了解决拖动div过快导致div突然停下来的问题
*/
let drag = false, position = null
div.addEventListener('mousedown', (e) => {
drag = true;
position = [e.clientX, e.clientY]
})
document.addEventListener('mousemove', (e) => {
if (!drag) {
return;
}
let x = e.clientX;
let y = e.clientY;
let dx = x - position[0]
let dy = y - position[1]
let left = parseInt(div.style.left || 0)
let top = parseInt(div.style.top || 0)
div.style.left = left + dx + 'px';
div.style.top = top + dy + 'px';
position = [x, y]
})
document.addEventListener('mouseup', () => {
drag = false
})
</script>
</html>
实现效果