需求:实现点击一个小方块 按下拖拽的功能。
实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="big">
<div class="small"></div>
</div>
</body>
</html>
<style>
.big {
width: 500px;
height: 500px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
position: absolute;
background-color: #eee;
}
.small {
width: 100px;
height: 100px;
border: 2px solid black;
position: absolute;
top: 0;
left: 0;
background-color: pink;
}
</style>
<script>
//获取big
var big = document.querySelector('.big');
var small = document.querySelector('.small');
//监听small的移动
small.onmousedown = function(e) {
//鼠标移动事件 必须按下才能触发移动
// 当快速的移动鼠标时,由于每移动1px就要重新获取位置的属性值,还需要不停的计算,此时会出现
// 计算误差,会造成鼠标移动时不在box事件源上,脱离box,不执行移动事件
// 解决方案: 将移动事件绑定在document上,不会出现脱离事件源的现象
document.onmousemove=function(e){
//计算移动的距离
let movex=(e.clientX-big.getBoundingClientRect().left)-small.offsetWidth/2
let movey=(e.clientY-big.getBoundingClientRect().top)-small.offsetHeight/2
//边界判断
movex<0 ? movex=0 : movex>big.offsetWidth-small.offsetWidth ? movex=big.offsetWidth-small.offsetWidth : movex=movex
movey<0 ? movey=0 : movey>big.offsetHeight-small.offsetHeight ? movey=big.offsetHeight-small.offsetHeight : movey=movey
small.style.left=movex+'px'
small.style.top=movey+'px'
}
//监听鼠标抬起
small.onmouseup=function(e){
document.onmousemove=null
}
}
</script>
getBoundingClientRect()使用 可参考: