简述
该示例为鼠标拖拽的简单实现案例
功能描述
- 鼠标在拖动区域按下时, 拖动盒子, 盒子跟随鼠标移动
- 鼠标松开时, 取消关联
代码
- index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>鼠标拖拽练习demo</title>
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<div id="box">
<div id="box-hand">拖拽区域</div>
</div>
</body>
</html>
<script>
// 鼠标按下时, 拖动盒子, 盒子跟随鼠标移动
// 鼠标松开时, 取消关联
// 关键点获取鼠标按下时, 鼠标在盒子中的位置, 在按下移动过程中鼠标相对盒子静止
// 获取盒子元素
const box = document.getElementById("box");
// 获取盒子拖拽区域元素
const drop = document.getElementById("box-hand");
drop.onmousedown = function (e) {
// 处理浏览器兼容问题
e = e || window.event;
// 鼠标按下时, 获取数据在盒子中的位置
// 鼠标在盒子中的位置 = 鼠标在页面的位置 - 盒子在页面的位置
console.log(box)
const x = e.pageX - box.offsetLeft;
const y = e.pageY - box.offsetTop;
// 鼠标移动
document.onmousemove = function (e) {
// 处理浏览器兼容问题
e = e || window.event;
// 获取盒子的坐标
// 盒子坐标 = 鼠标当前在页面的位置 - 鼠标在盒子中的位置
const boxX = e.pageX - x;
const boxY = e.pageY - y;
// 重置盒子位置, 使盒子相对鼠标静止
box.style.left = boxX + 'px';
box.style.top = boxY + 'px';
}
}
drop.onmouseup = function (e) {
// 处理浏览器兼容问题
e = e || window.event;
// 鼠标松开时, 移除鼠标事件
document.onmousemove = null;
}
</script>
-index.css
#box{
margin: auto;
width: 400px;
height: 300px;
background-color: darkgray;
position: absolute; // 需要改变盒子坐标必须脱离文档流
}
#box-hand {
width: 100%;
height: 35px;
color: beige;
line-height: 35px;
background-color: cadetblue;
cursor: move;
}