標簽拖拽
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>work-Drag</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
height: 300px;
width: 300px;
}
.b_1 {
position: absolute;
top: 100px;
left: 30px;
background-color: lightgreen;
z-index: 1;
}
.b_2 {
position: absolute;
top: 420px;
left: 430px;
background-color: lightsalmon;
z-index: 2;
}
.b_3 {
position: absolute;
top: 300px;
left: 200px;
background-color: lightcoral;
z-index: 3;
}
</style>
</head>
<body>
<div class="main">
<div class="box b_1"></div>
<div class="box b_2"></div>
<div class="box b_3"></div>
</div>
<script>
(() => {
class MoveDiv {
constructor(div) {
this.div = div
this.offsetX = 0
this.offsetY = 0
this.isDown = false
this.div.addEventListener('mousedown', (evt) => {
this.isDown = true
console.log(this.div.parentElement.children)
for (const d of this.div.parentElement.children) {
d.style.zIndex = 0
}
// 相對偏移坐標(鼠標在div中的坐標): 鼠標坐標 - div對象的左上角坐標
this.offsetX = evt.pageX - this.div.offsetLeft
this.offsetY = evt.pageY - this.div.offsetTop
this.div.style.zIndex = 999
})
this.div.addEventListener('mousemove', (evt) => {
if (this.isDown) {
// 計算當前div左上角坐標
// 當前鼠標坐標 - 相對偏移坐標
this.div.style.left = evt.pageX - this.offsetX + 'px'
this.div.style.top = evt.pageY - this.offsetY + 'px'
}
})
this.div.addEventListener('mouseup', (evt) => {
if (this.isDown) {
this.isDown = false
this.div.style.zIndex = 1
}
})
this.div.addEventListener('mouseleave', (evt) => {
if (this.isDown) {
this.isDown = false
this.div.style.zIndex = 1
}
})
}
}
let boxs = document.querySelectorAll('.main>.box')
for (box of boxs) {
new MoveDiv(box)
}
})()
</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ā)布平臺,僅提供信息存儲服務(wù)。