<!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>
image.png
event.clientX、event.clientY
鼠標(biāo)相對(duì)于瀏覽器窗口可視區(qū)域的X瘪板,Y坐標(biāo)(窗口坐標(biāo)),可視區(qū)域不包括工具欄和滾動(dòng)條逸吵。IE事件和標(biāo)準(zhǔn)事件都定義了這2個(gè)屬性
event.pageX宛乃、event.pageY
類似于event.clientX、event.clientY峭沦,但它們使用的是文檔坐標(biāo)而非窗口坐標(biāo)贾虽。這2個(gè)屬性不是標(biāo)準(zhǔn)屬性,但得到了廣泛支持吼鱼。IE事件中沒有這2個(gè)屬性蓬豁。
event.offsetX、event.offsetY
鼠標(biāo)相對(duì)于事件源元素(srcElement)的X,Y坐標(biāo)菇肃,只有IE事件有這2個(gè)屬性地粪,標(biāo)準(zhǔn)事件沒有對(duì)應(yīng)的屬性。
event.screenX琐谤、event.screenY
鼠標(biāo)相對(duì)于用戶顯示器屏幕左上角的X,Y坐標(biāo)蟆技。標(biāo)準(zhǔn)事件和IE事件都定義了這2個(gè)屬性