示例
完整代码
<!DOCTYPE html>
<html lang="zh">
<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>拖拽盒子</title>
<style>
body {
margin: 0;
padding: 0;
}
.container {
position: fixed;
z-index: 1000;
width: 100%;
height: 100%;
background: #00000073;
}
.box {
width: 520px;
height: 200px;
background: #fff;
}
.box_drag {
height: 60px;
width: 100%;
line-height: 60px;
text-align: center;
border-bottom: 1px dashed #ccc;
user-select: none;
color: #69c0ff;
cursor: move;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
<div class="box_drag">鼠标移动上来拖动盒子</div>
</div>
</div>
<script>
(function dragDom() {
let dragDomMove = document.querySelector('.box')
let dragDom = document.querySelector('.box_drag')
let drag = true
let location = [0, 0]
if (!drag) return
// 事件按下
dragDom.onmousedown = function(event) {
dragDomMove.style.position = "absolute"
let X, Y
let maxPosition = [window.innerWidth, window.innerHeight] //最大滚动位置
let boxSize = [dragDomMove.offsetWidth, dragDomMove.offsetHeight] //盒子宽高
let curPosition = [event.clientX, event.clientY] // 获取当前的x、y轴距离
let prePosition = getDragMoveAxis(dragDomMove.style.transform) // 获取鼠标在方块内的轴距
let innerX = curPosition[0] - prePosition[0] // 获取鼠标在方块内的x轴距
let innerY = curPosition[1] - prePosition[1] // 获取鼠标在方块内的y轴距
// 事件拖动
document.onmousemove = function(e) {
// 边界限制
X = e.clientX - event.offsetX < 0 ? 0 : maxPosition[0] - e.clientX > 0 ? e.clientX - innerX :
X
Y = e.clientY - event.offsetY < 0 ? 0 : maxPosition[1] - e.clientY > 0 ? e.clientY - innerY :
Y
if (maxPosition[0] - X > boxSize[0]) {
location[0] = X
} else {
location[0] = maxPosition[0] - boxSize[0]
}
if (maxPosition[1] - Y > boxSize[1]) {
location[1] = Y
} else {
location[1] = maxPosition[1] - boxSize[1]
}
dragDomMove.style.transform = `translate(${location[0]}px, ${location[1]}px)`
}
// 事件清除
document.onmouseup = function() {
document.onmousemove = null
document.onmouseup = null
}
}
})()
function getDragMoveAxis(data) {
var clientArr = data.match(/\d+(\.\d+)?/g) || [0, 0];
//字符串数组转数字数组
return clientArr.map(Number)
}
</script>
</body>
</html>