拖拽包含三个步骤:鼠标按下(mousedown)、鼠标移动(mousemove)、鼠标抬起(mouseup);
拖拽过程:鼠标按下不动,拖着鼠标移动,当鼠标抬起时取消移动。
<!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>
#box {
width: 200px;
height: 200px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
//根据id获取到div赋给变量box
var box = document.querySelector("#box");
//给box添加监听事件
box.addEventListener("mousedown", function(e) {
//获取事件的兼容写法
e = e || window.event;
//获取鼠标点击到其最近父元素的距离
var distanceX = e.offsetX;
var distanceY = e.offsetY;
//鼠标移动的函数
function move(e) {
e = e || window.event;
//使鼠标与box同步移动,即box的left值为鼠标点击处到可视区的距离减去到其最近父元素box的距离
var left = e.clientX - distanceX;
var top = e.clientY - distanceY;
//控制鼠标移动范围
if (left < 0) left = 0;
if (left >= window.innerWidth - box.offsetWidth) left = window.innerWidth - box.offsetWidth;
if (top < 0) top = 0;
if (top >= window.innerHeight - box.offsetHeight) top = window.innerHeight - box.offsetHeight;
//给盒子添加位置坐标
box.style.left = left + "px";
box.style.top = top + "px";
}
//给box添加移动事件
document.addEventListener("mousemove", move);
//当鼠标抬起时,取消移动事件
document.addEventListener("mouseup", function() {
document.removeEventListener("mousemove", move);
})
})
</script>
</body>
</html>