function drag(ele) {
const config = {
mark: 0,
x: 0,
y: 0,
left: ele.offsetLeft,
top: ele.offsetTop,
newLeft: 0,
newTop: 0,
}
ele.onmousedown = (e) => {
config.mark = 1;
config.x = e.clientX;
config.y = e.clientY;
}
document.addEventListener('mousemove', (e) => {
if (!config.mark) {
return;
}
ele.style.left = config.left + e.clientX - config.x + 'px';
ele.style.top = config.top + e.clientY - config.y + 'px';
// 记录新的 left 和 top
config.newLeft = config.left + e.clientX - config.x;
config.newTop = config.top + e.clientY - config.y;
});
document.addEventListener('mouseup', (e) => {
if (config.mark) {
config.left = config.newLeft;
config.top = config.newTop;
}
config.mark = 0;
});
}
const div = document.querySelector('div');
const p = document.querySelector('p');
drag(div);
drag(p);
/*
<div style="background: rgb(0, 0, 0); width: 100px; height: 100px; position: absolute;"></div>
<p style="background: rgb(155, 155, 155); width: 100px; height: 100px; position: absolute;"></p>
*/