<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
#box {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
background: red;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
const oBox = document.getElementById('box');
function myDrag(ele, wrap) {
let disL,
disT;
let drag = false;
//鼠标按下的时候,先求出鼠标到盒子边框上的距离
ele.onmousedown = function(e) {
drag = true;
disL = e.clientX - ele.offsetLeft;
disT = e.clientY - ele.offsetTop;
}
document.onmousemove = function(e) {
if (drag) {
ele.style.left = e.clientX - disL + 'px';
ele.style.top = e.clientY - disT + 'px';
}
}
ele.onmouseup = function(e) {
drag = false;
}
}
myDrag(oBox, document);
</script>
</body>
</html>