效果如下
- 首先可以先获得鼠标在盒子中点击的位置,点击哪里位置就确定在哪里且不会变化,首先需要:mousedown(鼠标按下),mouseup(鼠标抬起),mousemove()鼠标移动三个事件。
//确定鼠标的点击位置,点击哪里就保持不变
let x = 0,
y = 0;
box.onmousedown = function (e) {
//确定鼠标的点击位置,点击哪里就保持不变
//鼠标x轴的距离=点击位置的页面x轴的距离-盒子距离页面左面的距离
x = e.pageX - box.offsetLeft;
//鼠标y轴的距离=点击位置的页面y轴的距离-盒子距离页面上面的距离
y = e.pageY - box.offsetTop;
}
- 接下来就是鼠标按下之后移动时,盒子可以被拖拽走。
window.onmousemove = function (e) {
// 阻止默认行为,防止文字被拖动
e.preventDefault();
if (canMove) {
//距离左面的距离=鼠标点击的页面X轴的距离-鼠标点击的x轴位置
let left = e.pageX - x;
//距离上面的距离=鼠标点击的页面y轴的距离-鼠标点击的y轴位置
let top = e.pageY - y;
//防止盒子超出屏幕的边缘
if (left < 0) left = 0
if (top < 0) top = 0
if (left > maxLeft) left = maxLeft;
if (top > maxTop) top = maxTop;
box.style.left = left + "px";
box.style.top = top + "px";
}
}
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽案例</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 150px;
height: 150px;
cursor: move;
background-color: red;
position: absolute;
}
</style>
</head>
<body>
<div class="box">
aaaaaaa
</div>
<script>
let canMove = false;
let box = document.querySelector(".box");
let x = 0,
y = 0;
//屏幕的宽度-自身的宽度=可移动的最大宽度
let maxLeft = window.innerWidth - box.offsetWidth;
//屏幕的高度-自身的高度=可移动的最大高度
let maxTop = window.innerHeight - box.offsetHeight;
box.onmousedown = function (e) {
//只有鼠标按下onmousemove才会执行
canMove = true;
//确定鼠标的点击位置,点击哪里就保持不变
x = e.pageX - box.offsetLeft;
y = e.pageY - box.offsetTop;
}
window.onmousemove = function (e) {
// 阻止默认行为,防止文字被拖动
e.preventDefault();
if (canMove) {
//距离左面的距离=鼠标点击的页面X轴的距离-鼠标点击的x轴位置
let left = e.pageX - x;
//距离上面的距离=鼠标点击的页面y轴的距离-鼠标点击的y轴位置
let top = e.pageY - y;
if (left < 0) left = 0
if (top < 0) top = 0
if (left > maxLeft) left = maxLeft;
if (top > maxTop) top = maxTop;
box.style.left = left + "px";
box.style.top = top + "px";
}
}
window.onblur = function (e) {
canMove = false;
}
window.onmouseup = function (e) {
canMove = false;
}
</script>
</body>
</html>