1.当我们鼠标按下的时候,获取鼠标在盒子内的坐标 (当鼠标按下时,鼠标在盒子中的坐标是固定的)
2.当鼠标移动时,得到鼠标在页面中的坐标 减去鼠标在盒子中的坐标 (当鼠标移动时,我们得到的坐标是一个一直都在变化的值)
3.在把得到的值赋给 模态框 (值一直是变化的,当我们把值给模态框时,模态框就会跟着鼠标移动)
代码如下:
<!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>
<style>
.box {
width: 300px;
height: 200px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
cursor: move;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
//当我们鼠标按下的时候,获取鼠标在盒子内的坐标 (当鼠标按下时,鼠标在盒子中的坐标是固定的)
// 当鼠标移动时,得到鼠标在页面中的坐标 减去鼠标在盒子中的坐标 (当鼠标移动时,我们得到的坐标是一个一直都在变化的值)
// 在把得到的值赋给 模态框 (值一直是变化的,当我们把值给模态框时,模态框就会跟着鼠标移动)
var box = document.querySelector('.box');
box.addEventListener('mousedown',function(e){
//鼠标按下 得到鼠标在盒子中的坐标
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
//鼠标移动的时候,把鼠标在页面中的坐标,减去鼠标在盒子内的坐标就是模态框的left和top值
document.addEventListener('mousemove',move);
function move(e){
box.style.left = e.pageX - x + 'px';
box.style.top = e.pageY - y + 'px';
}
//鼠标弹起,就让鼠标移动事件解除
document.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',move)
});
})
</script>
</body>
</html>
效果: