实现的原理:
根据上面的图可以算出移动后的盒子的left和top:
鼠标距离边界的值:
ev.pageY - box.top
ev.pageX - box.left
box2.top = ev2.pageY - (ev1.pageY - box1.top)
= ev2.pageY - ev1.pageY + box1.top
box2.left = ev2.pageX - (ev1.pageX - box1.left)
= ev2.pageX - ev1.pageX + box1.left
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DRAG-拖拽</title>
</head>
<style>
html, body {
height: 100%;
overflow: hidden;
}
.box {
box-sizing: border-box;
width: 100px;
height: 100px;
background-color: lightblue;
position: absolute;
top: 0px;
left: 0px;
cursor: move;
}
</style>
<body>
<div class="box"></div>
<script>
let box = document.querySelector(".box");
box.onmousedown = down;
function down(ev) {
// 把鼠标的起始位置和盒子的起始位置存为盒子的自定义属性
this.pageX = ev.pageX;
this.pageY = ev.pageY;
this.left = this.offsetLeft;
this.top = this.offsetTop;
// 接下来再给盒子绑定MOVE和UP方法:只有鼠标按下的时候才去绑定移动和抬起
// 把鼠标和当前盒子拿绳子绑在一起
this.onmousemove = move;
this.onmouseup = up;
this.setCapture(); //只支持IE和火狐
}
function move(ev) {
let curT = ev.pageY - this.pageY + this.top,
curL = ev.pageX - this.pageX + this.left;
// 边界处理
let minL = 0,
maxL = document.documentElement.clientWidth - this.offsetWidth,
minT = 0,
maxT = document.documentElement.clientHeight - this.offsetHeight;
curL = curL < minL ? minL : (curL > maxL ? maxL : curL);
curT = curT < minT ? minT : (curT > maxT ? maxT : curT);
this.style.left = curL + 'px';
this.style.top = curT + 'px';
}
function up(ev) {
// 鼠标抬起,把MOVE和UP都移除掉
// 解绑
this.onmousemove = null;
this.onmouseup = null;
this.releaseCapture(); //只支持IE和火狐
}
</script>
</body>
</html>
setCapture和releaseCapture方法:为了防止鼠标滑的过快,导致鼠标焦点丢失,盒子没办法继续跟着移动,所以将鼠标和盒子绑在一起。
由于谷歌不支持setCapture和releaseCapture方法,所以,换个思路:
由于鼠标的滑动不会离开整个document,所以将鼠标的移动和抬起放在document下。
<script>
let box = document.querySelector(".box");
box.onmousedown = down;
function down(ev) {
// 把鼠标的起始位置和盒子的起始位置存为自定义属性
this.pageX = ev.pageX;
this.pageY = ev.pageY;
this.left = this.offsetLeft;
this.top = this.offsetTop;
// 接下来再给盒子绑定MOVE和UP方法:只有鼠标按下的时候才去绑定移动和抬起
// 谷歌的绑定方法:鼠标在document中操作,注意this的处理
document.onmousemove = move.bind(this);
document.onmouseup = up.bind(this);
}
function move(ev) {
let curT = ev.pageY - this.pageY + this.top,
curL = ev.pageX - this.pageX + this.left;
// 边界处理
let minL = 0,
maxL = document.documentElement.clientWidth - this.offsetWidth,
minT = 0,
maxT = document.documentElement.clientHeight - this.offsetHeight;
curL = curL < minL ? minL : (curL > maxL ? maxL : curL);
curT = curT < minT ? minT : (curT > maxT ? maxT : curT);
this.style.left = curL + 'px';
this.style.top = curT + 'px';
}
function up(ev) {
// 鼠标抬起,把MOVE和UP都移除掉
// 谷歌的解绑方法:
document.onmousemove = null;
document.onmouseup = null;
}
</script>