鼠標移動拖曳代碼示例
<!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"
}
}
// 鼠標左鍵在網(wǎng)頁中抬起,停止拖動
document.onmouseup = function() {
// 解除移動事件
document.onmousemove = null
}
</script>
</body>
</html>