鼠标拖拽div移动
效果图:
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>鼠标拖拽div移动</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
position: relative;
background-color: #FF0000;
}
</style>
<script type="text/javascript">
window.onload = function(){
let boxx = 0;
let boxy = 0;
var isDown = false;
//用于存储新的光标坐标
let mosx = 0;
let mosy = 0;
let mosx2 = 0;
let mosy2 = 0;
//获取box
const box = document.getElementById('box');
//box元素鼠标按下触发事件
box.onmousedown = function(e){
//获取并记录鼠标第一次按下时光标的坐标
mosx = e.pageX;
mosy = e.pageY;
//开关打开
isDown = true;
};
//设置鼠标移动事件
window.onmousemove = function(e){
if (!isDown) {
return;
}
//获取光标移动时光标的新坐标
mosx2 = e.pageX;
mosy2 = e.pageY;
//计算box的新坐标
boxx += (mosx2 - mosx);
boxy += (mosy2 - mosy);
//将光标的旧坐标更新
mosx = mosx2;
mosy = mosy2;
//移动box
box.style.top = boxy + "px";
box.style.left = boxx + "px";
};
//鼠标放开触发事件
box.onmouseup = function(){
isDown = false;
};
};
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>