使用transform: translate,offsetLeft的值永远是0,是无法检测到吗?定位是可以的。
<!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 {
width: 300px;
height: 300px;
background-color: skyblue;
transform: translate(100px, 100px);
}
</style>
</head>
<body>
<div></div>
<script>
// debugger
const div = document.querySelector('div');
let x = 0;
let y = 0;
function handleClient(ev) {
ev.target.style.transform = `translate(${ev.clientX - x}px,${ev.clientY - y}px)`;
}
div.addEventListener('mousedown', (ev) => {
x = ev.clientX - ev.target.offsetLeft;
y = ev.clientY - ev.target.offsetTop;
console.log(`x${x}, y${y}`);
console.log('offsetLeft ', ev.target.offsetLeft, 'offsetTop ', ev.target.offsetTop);
console.log('ev.clientX ', x, 'ev.clientY ', y);
console.log('ev.clientX - x: ', ev.clientX - x, 'ev.clientY - y: ', ev.clientY - y);
});
</script>
</body>
</html>
规范明确说明忽略变换