<!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>
body{
width: 100%;
height: 100vh;
display: flex;
}
#box{
width: 500px;
height: 500px;
background-color: aquamarine;
display: flex;
margin: auto;
position: relative;
}
#drag{
width: 50px;
height: 50px;
background-color: lightcoral;
margin: auto;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="drag"></div>
</div>
<script>
class Drag{
constructor(child,parent){
this.child=child
this.parent=parent
this.child.addEventListener("mousedown",this.mousedown)
this.child.addEventListener("mousemove",this.mousemove)
this.child.addEventListener("mouseup",this.mouseup)
this.parentOffsetLeft=this.parent.offsetLeft
this.parentOffsetTop=this.parent.offsetTop
this.childOffsetLeft=this.child.offsetLeft
this.isDown=false
}
mousedown=(evt)=>{
this.isDown=true
this.X=evt.offsetX
this.Y=evt.offsetY
}
mousemove=(evt)=>{
if(!this.isDown){
return
}
this.diffX=evt.clientX-this.parentOffsetLeft-this.X
this.diffY=evt.clientY-this.parentOffsetTop-this.Y
if(this.diffX<0){
this.diffX=0
}else if(this.diffX>this.parent.offsetWidth-this.child.offsetWidth){
this.diffX=this.parent.offsetWidth-this.child.offsetWidth
}
if(this.diffY<0){
this.diffY=0
}else if(this.diffY>this.parent.offsetHeight-this.child.offsetHeight){
this.diffY=this.parent.offsetHeight-this.child.offsetHeight
}
this.child.style.top=this.diffY+"px"
this.child.style.left=this.diffX+"px"
}
mouseup=(evt)=>{
this.isDown=false
}
}
new Drag(document.getElementById("drag"),document.getElementById("box"))
</script>
</body>
</html>
event.clientX、event.clientY
鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条。IE事件和标准事件都定义了这2个属性
event.pageX、event.pageY
类似于event.clientX、event.clientY,但它们使用的是文档坐标而非窗口坐标。这2个属性不是标准属性,但得到了广泛支持。IE事件中没有这2个属性。
event.offsetX、event.offsetY
鼠标相对于事件源元素(srcElement)的X,Y坐标,只有IE事件有这2个属性,标准事件没有对应的属性。
event.screenX、event.screenY
鼠标相对于用户显示器屏幕左上角的X,Y坐标。标准事件和IE事件都定义了这2个属性