JavaScript高级手记(原生拖拽效果)
<!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>
html,
body {
height: 100%;
overflow: hidden;
}
.box {
position: absolute;
top: 100px;
left: 200px;
width: 100px;
height: 100px;
background: lightskyblue;
cursor: move;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
let box = document.querySelector('.box');
let screen = document.documentElement,
boxData = box.getBoundingClientRect(),
minL = 0,
minT = 0,
maxL = screen.clientWidth - boxData.width,
maxT = screen.clientHeight - boxData.height;
function down(ev) {
let {
top,
left
} = this.getBoundingClientRect();
this.boxTop = top;
this.boxLeft = left;
this.mouseX = ev.clientX;
this.mouseY = ev.clientY;
this.moveFn = move.bind(this);
this.upFn = up.bind(this);
window.addEventListener('mousemove', this.moveFn);
window.addEventListener('mouseup', this.upFn);
}
function move(ev) {
let curL = ev.clientX - this.mouseX + this.boxLeft,
curT = ev.clientY - this.mouseY + this.boxTop;
curL = curL < minL ? minL :(curL > maxL ? maxL: curL);
curT = curT < minT ? minT :(curT > maxT ? maxT: curT);
box.style.left = curL + 'px';
box.style.top = curT + 'px';
}
function up(ev) {
window.removeEventListener('mousemove', this.moveFn);
window.removeEventListener('mouseup', this.upFn);
}
box.addEventListener('mousedown', down);