用鼠标事件实现最简单的元素移动
实现效果
用mousedown、mousemove、mouseup鼠标事件实现元素的移动。
- mousedown:按下任意(左、中、右)鼠标键是触发。
- mousemove:鼠标在元素上移动时触发。
- mouseup:放开鼠标按键时触发。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>实现简单的元素移动</title>
<style>
*{
padding: 0;
margin: 0;
border : 0;
}
#box{
width: 100px;
height: 100px;
background-color: #f60;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box = document.getElementById("box");
box.onmousedown = (e)=>{ //鼠标按下
let downClientX = e.clientX; // 鼠标到浏览器视口左边的距离
let downClientY = e.clientY; // 鼠标到浏览器视口定边的距离
let offsetLeft = box.offsetLeft; // 元素border左边距离父元素border左边或者body元素border左边的距离
let offsetTop = box.offsetTop; // 元素border顶部距离父元素顶部或者body元素border顶部的距离
box.onmousemove = (e)=>{ //鼠标移动
let timer = null;
timer = setTimeout(()=>{
box.style.left = e.clientX - downClientX + offsetLeft + "px";
box.style.top = e.clientY - downClientY + offsetTop + "px";
},20);
box.onmouseup = ()=>{ //鼠标放开
box.onmousemove = null;
}
}
}
</script>
</body>
</html>
开发工具