鼠标移动拖曳代码示例
<!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
{
/* 绝对定位 */
position: absolute;
width: 400px;
height: 300px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
// 获取box的div标签
let box = document.getElementById("box")
// 鼠标在box上左键按下时:拖动
box.onmousedown = function(e) {
// 记录鼠标在div上的位置 offsetX, offsetY
let offsetX = e.offsetX
let offsetY = e.offsetY
console.log(offsetX,
"offsetX")
console.log(offsetY,
"offsetY")
// 鼠标开始在窗口中移动
document.onmousemove = function(e2) {
// 获取鼠标在窗口中的位置
let clientX = e2.clientX
let clientY = e2.clientY
console.log(clientX,
"clientX")
console.log(clientY,
"clientY")
// 计算div的位置
_left = clientX - offsetX
_top = clientY - offsetY
console.log(_left,
"left")
console.log(_top,
"top")
// 定位div位置
box.style.left = _left + "px"
box.style.top = _top + "px"
}
}
// 鼠标左键在网页中抬起,停止拖动
document.onmouseup = function() {
// 解除移动事件
document.onmousemove = null
}
</script>
</body>
</html>