HTML
<div class="box"></div>
CSS
.box{
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
记得添加定位,不然移动不了
分为三个事件,鼠标点击下去(onmousedown),鼠标移动时候(onmousemove),鼠标松开(mouseup事件)
onmousedown事件
我们需要这个事件计算鼠标的位置,和div真实移动距离
div的真实移动距离=鼠标的位置减去这个差值
差值 = 鼠标到最左边的距离减去div到最左边的距离
box.onmousedown = function (e) {
var e = e ||window.event;//要用event这个对象来获取鼠标的位置
x = e.clientX - box.offsetLeft;
y = e.clientY - box.offsetTop;
isDrop = true;//判断能否移动div,true表示可以移动
}
onmousemove事件
为了防止鼠标移动过快时间无法正确处理所以事件绑定到document上
同时我们需要防止div移动出屏幕:获取屏幕的宽高-div的宽高就是我们最大移动范围
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
同时我们还需要设定div的移动范围为0到最大
movex=Math.max(0,movex);
movey=Math.max(0,movey);
结合起来就是
movex = Math.min(maxX,Math.max(0,movex));
movey = Math.min(maxY,Math.max(0,movey));
完整的事件代码:
document.onmousemove = function (e) {
if(isDrop){
var e = e||window.event;
var movex = e.clientX-x;
var movey = e.clientY-y;
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
movex = Math.min(maxX,Math.max(0,movex));
movey = Math.min(maxY,Math.max(0,movey));
box.style.left = movex + "px";
box.style.top = movey + "px";
}
else {
return ;
}
}
onmouseup事件
将isDrop改为false,设置为不可移动
document.onmouseup = function() {
isDrop = false; //设置为false不可移动
}
整个的完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
</div>
<script>
var x,y;
var box = document.getElementsByClassName("box")[0];
var isDrop = false;
box.onmousedown = function (e) {
var e = e ||window.event;
x = e.clientX - box.offsetLeft;
y = e.clientY - box.offsetTop;
isDrop = true;
}
document.onmousemove = function (e) {
if(isDrop){
var e = e||window.event;
var movex = e.clientX-x;
var movey = e.clientY-y;
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
movex = Math.min(maxX,Math.max(0,movex));
movey = Math.min(maxY,Math.max(0,movey));
box.style.left = movex + "px";
box.style.top = movey + "px";
}
else {
return ;
}
}
document.onmouseup = function() {
isDrop = false; //设置为false不可移动
}
</script>
</body>
</html>