代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
position: absolute;
width: 500px;
height: 300px;
border: 1px solid #cccccc;
background-color: #999999;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.son {
width: 200px;
height: 100px;
background-color: #fff;
font-size: 25px;
text-align: center;
line-height: 100px;
margin: 10px auto;
-moz-user-select: none;
-webkit-user-select: none;
user-select: none;
}
.son:hover {
cursor: move;
}
</style>
</head>
<body>
<div class="father">
<div class="son">拖拽移动</div>
</div>
</body>
<script>
var son = document.querySelector('.son')
var father = document.querySelector('.father')
son.addEventListener('mousedown', function(e) {
var x = e.pageX - father.offsetLeft
var y = e.pageY - father.offsetTop
function move(e) {
father.style.top = e.pageY - y + 'px'
father.style.left = e.pageX - x + 'px'
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move)
})
})
</script>
</html>
因为要拖动,所以父盒子要加定位,但需要注意的是要使用 absolute 定位,使用 relative 定位的话是有问题的(相对于之前的位置定位)
分为三个事件 , 鼠标按下事件、鼠标拖动事件、鼠标抬起事件。当鼠标按下时获得鼠标在父盒子里面的坐标(x,y),鼠标开始移动的时候用鼠标移动后的坐标减去鼠标在父盒子里面的坐标,把所得的值赋给父盒子的left和top。鼠标抬起时 移除鼠标移动事件。
使用-moz-user-select: none; -webkit-user-select: none; user-select: none;来禁止选中