之前总是把移动事件绑定在div上,结果鼠标移动太快,div跟不上,事件就获取不到了,div就卡住了。
现在将移动事件和取消事件绑定在document上,即使鼠标移出浏览器,div也能跟着移动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="123124" class="win">
<div class="title">标题栏</div>
</div>
<script>
const win=document.getElementById('123124')
const title=win.getElementsByClassName('title')[0]
const drag={
status:false,
lastX:null,
lastY:null
}
title.onmousedown=(event)=>{
if(event.button===0){
document.onmousemove=(event)=>{
if(drag.status){
let mx=event.clientX-drag.lastX
let my=event.clientY-drag.lastY
drag.lastX=event.clientX
drag.lastY=event.clientY
let top=win.offsetTop+my
win.style.left=win.offsetLeft+mx+'px';
win.style.top=top<0?0:top+"px"
}
}
document.onmouseup=(event)=>{
if(event.button===0){
drag.status=false
document.onmousemove=null
document.onmouseup=null
}
}
drag.status=true
drag.lastX=event.clientX
drag.lastY=event.clientY
}
}
</script>
<style>
.win{
width: 400px;
height: 300px;
background: white;
box-shadow: 1px 1px 5px 2px rgba(0,0,0,0.2);
position: absolute;
top: 100px;
left: 100px;
}
.title{
height: 25px;
background: #e2e2e2;
padding: 5px;
user-select: none;
}
body{
position: relative;
background: #e2e2e2;
overflow: hidden;
}
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
</body>
</html>
代码可以粘到下面在线编辑器试试