前端拖拽的简单实现
鼠标按下拖动松开时鼠标的位置分析:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>拖找</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
width: 100%;
}
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<body>
<div id="box1"></div>
</body>
<script type="text/javascript">
window.onload = function () {
let box1 = document.getElementById("box1");
box1.onmousedown = function (e) {
console.log(e.clientX, box1.offsetLeft);
//div的偏移量.clientX - 元素.offeetLeft
let ol = e.clientX - box1.offsetLeft;
let ot = e.clientY - box1.offsetTop;
// 给document绑定一个onmousemove事件
document.onmousemove = function (event) {
event = event || window.event;
let left = event.clientX - ol;
let top = event.clientY - ot;
//修改box1的位置
box1.style.left = left + "px";
box1.style.top = top + "px";
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
};
};
</script>
</html>

浙公网安备 33010602011771号