1,首先box盒子要绝对定位
2,算出鼠标离box盒子的位置
3,最后赋值left和top值
<!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>
* {
padding: 0;
margin: 0;
}
div {
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #ccc;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector('div'); //获取元素
div.addEventListener('mousedown', function(e) { // 鼠标按下 事件
var x = e.pageX - div.offsetLeft; //鼠标在文档里面的 x坐标 减去 div离left的值 等于 鼠标在盒子内的坐标
var y = e.pageY - div.offsetTop; //鼠标在文档里面的 y坐标 减去 div离top的值 等于 鼠标在盒子内的坐标
document.addEventListener('mousemove', fn); //在document里面鼠标移动事件
function fn(e) {
div.style.left = e.pageX - x + 'px'; //div的left值 等于 鼠标在页面中的值减去 盒子内的坐标
div.style.top = e.pageY - y + 'px';
}
document.addEventListener('mouseup', function() { //最后添加 鼠标弹起事件
document.removeEventListener('mousemove', fn); //移除 addEventListener() 方法添加的 "mousemove" 事件:
});
});
</script>
</body>
</html>