原生js实现 拖拽元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="box" style="width: 100px;height: 100px;background-color:red;position:absolute"></div>
</body>
<script>
let box = document.querySelector("#box")
let body = document
box.style.left = box.offsetLeft + "px"
box.style.top = box.offsetTop + "px"
box.addEventListener("mousedown", draw1)
box.addEventListener("mouseup", draw2)
let distanceX = 0
let distanceY = 0
function draw1(e) {
console.log('按下')
body.addEventListener("mousemove", draw3)
distanceX = e.clientX - parseInt(box.style.left.split("px")[0])
distanceY = e.clientY - parseInt(box.style.top.split("px")[0])
}
function draw2(e) {
console.log("松起")
body.removeEventListener("mousemove", draw3)
}
function draw3(e) {
console.log("鼠标X:" + e.clientX, "鼠标y:" + e.clientY)
box.style.left = e.clientX - distanceX + "px"
box.style.top = e.clientY - distanceY + "px"
}
</script>
</html>