关于鼠标拖拽,分三步
1-按下鼠标
2-移动鼠标,获取鼠标相对元素和窗口的位置(offset和client)
3-松开鼠标
<!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>Document</title>
<style>
*{margin: 0; padding: 0;}
#box1{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div id="box1">
</div>
<script>
window.onload = function() {
var box1 = document.querySelector('#box1')
// 鼠标按下
box1.onmousedown = (e) => {
// 获取鼠标相对于box元素的位置
e = e || window.event
var divX = e.offsetX
var divY = e.offsetY
// 鼠标移动,将鼠标位置给到box1
document.onmousemove = (e) => {
e = e || window.event
var x = e.clientX - divX >= 0 ? (e.clientX - divX) : 0
var y = e.clientY - divY >= 0 ? (e.clientY - divY) : 0
box1.style.left = x + 'px'
box1.style.top = y + 'px'
}
}
// 鼠标松开
box1.onmouseup = () => {
document.onmousemove = null
}
}
</script>
</body>
</html>