<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 200px;
background-color: slateblue;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box"></div>
/**
拖拽
1. 触发的事件源
box div
box div / document
box div
2. 触发的事件类型
按下
移动
抬起
3. 移动的距离
最新的定位 - 鼠标按下时的定位 === 移动的距离
4. 移动到哪里
元素的初始位置 + 移动的距离 === 移动到哪里
*/
<script>
const box = documen.querySelector(".box")
let flag = false
let startX = 0
let startY = 0
let startLeft = 0
let startTop = 0
box.onmousedown = function(e) {
flag = true
startX = e.clientX
startY = e.clientY
startLeft = box.offsetLeft
startTop = box.offsetTop
}
document.onmousemove = function(e) {
if(flag === false) return
let moveX = e.client - startX
let moveY = e.client - startY
let left = startLeft + moveX
let top = startTop + moveY
if(left < 0) {left = 0}
if(top < 0) {top = 0}
let maxLeft = document.documentElement.clientWidth
let maxTop = document.documentElement.clientHeight
if(left > maxLeft) {left = maxLeft}
if(top > maxTop) {top = maxTop}
box.style.left = left + "px"
box.style.top = top + "px"
}
box.onmouseup = function () {
flag = false
}
</script>