首先在HTML页面写一个div盒子标签,并设置宽高和背景色以便观察和区分
- HTML代码
<!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>
*{ //去除浏览器默认样式
margin: 0;
padding: 0;
}
.demo{
width: 100px;
height: 100px;
background-color: #aaa;
}
</style>
</head>
<body>
<div class="demo">
1111
</div>
</body>
</html>
2.浏览器效果
当我们鼠标在div标签内部按下不松的时候可以移动div盒子的位置
1.首先我们用到浏览器的 e 事件
2.然后通过onmousedown , onmouseup , ommousemove三个监听鼠标操作触发e事件,从而获取我们需要的位置信息,即offsetwidth offsetheight
<script>
let demo=document.getElementsByClassName('demo')[0]//获取盒子dom节点
let canMove=false//用于判断鼠标是否点击在盒子上
demo.onmousedown=function(e){ //当鼠标点击在盒子里面时改变canMove的值为true,从而触发window.onmousemove来去全局控制盒子移动
canMove = true;
}
window.onmouseup=function(){//当鼠标松开是canMove为false,使得window.onmousemove控制盒子停下来
canMove = false;
}
window.onmousemove=function(e){
if(canMove){//当canMove为true时控制盒子的左边和顶部距离来移动盒子
demo.style.left = e.pageX + "px" //e.pageX鼠标到body左侧的距离
demo.style.top = e.pageY + 'px' //e.pageY鼠标到body顶部的距离
}
}
</script>
当这一步完成时我们点击div就可以拖动它了,但是你会发现你鼠标按住拖动div时,鼠标div左上角会自动聚焦到鼠标位置而不是你按下的位置
松开鼠标时div盒子停止移动并停留在当前位置
1.调整鼠标按下时的位置为点击位置
<script>
let demo=document.getElementsByClassName('demo')[0]
let canMove=false//用于判断鼠标是否点击在盒子上
let x=0,y=0
demo.onmousedown=function(e){//监听鼠标在盒子内按下
//demo.offsetLeft盒子到body左侧的距离
//demo.offsetTop盒子到body顶部的距离
x=e.pageX-demo.offsetLeft
y=e.pageY-demo.offsetTop
canMove = true;
}
window.onmouseup=function(){//监听鼠标松开
canMove = false;
}
window.onmousemove=function(e){
if(canMove){
let left=e.pageX-x
let top=e.pageY-y
demo.style.left = left + "px"
demo.style.top = top + 'px'
}
}
</script>
- 限制盒子移动范围不超出body
window.onmousemove=function(e){
if(canMove){
let left=e.pageX-x
let top=e.pageY-y
if (left < 0) left = 0
if (top < 0) top = 0
let maxLeft = window.innerWidth - demo.offsetWidth
let maxTop = window.innerHeight - demo.offsetHeight
if (left > maxLeft) left = maxLeft
if (top > maxTop) top = maxTop
demo.style.left = left + "px"
demo.style.top = top + 'px'
}
}
3.解决鼠标失焦时盒子不会停止的bug
window.onmousemove=function(e){
e.preventDefault(); //阻止浏览器默认行为
if(canMove){
let left=e.pageX-x
let top=e.pageY-y
if (left < 0) left = 0
if (top < 0) top = 0
let maxLeft = window.innerWidth - demo.offsetWidth
let maxTop = window.innerHeight - demo.offsetHeight
if (left > maxLeft) left = maxLeft
if (top > maxTop) top = maxTop
demo.style.left = left + "px"
demo.style.top = top + 'px'
}
}
window.onblur = function () {
//失焦事释放canMove将其置为false
canMove = false;
};
demo.oncontextmenu = function (e) {
//禁用右键菜单
e.preventDefault();
};