标签拖拽
<!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>