鼠標移動拖曳

鼠標移動拖曳代碼示例

<!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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容