主要是使用了event.pageX
和dom.getBoundingClientRect
属性和方法
HTML
<!DOCTYPE html>
<html lang="zh-cn">
<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>
body {
height: 100vh;
}
.container {
position: relative;
height: inherit;
}
.moving {
position: absolute;
width: 100px;
height: 100px;
background-color: khaki;
}
</style>
</head>
<body>
<div id="container">
<div class="moving"></div>
</div>
<script src="./index.js"></script>
</body>
</html>
JavaScript
let item = document.getElementById('container')
item.addEventListener('mousedown', bindMoving)
item.addEventListener('mouseup', unBindMoving)
function bindMoving(event) {
if (event.target.className === 'moving') {
let x = event.pageX - event.target.getBoundingClientRect().x
let y = event.pageY - event.target.getBoundingClientRect().y
let k = { x, y }
tmp = moving.bind(this, k)
event.target.addEventListener('mousemove', tmp)
event.target.addEventListener('mouseleave', unBindMoving)
}
}
function unBindMoving(event) {
event.target.removeEventListener('mousemove', tmp)
}
function moving(k) {
event.target.style.cssText = `left: ${event.pageX - k.x}px; top: ${event.pageY - k.y}px;`
}
function tmp() {}