JSFiddle - React, Tailwind, and code Playground
by brokenbonesdd
HTML
<div class="mouse-style">
拖拽
</div>
CSS
.mouse-style {
position: absolute;
width: 100px;
height: 100px;
background-color: blue;
}
JavaScript
let range = {
x: 0,
y: 0
}; // 鼠标元素偏移量
let lastPos = {
x: 0,
y: 0
};
let flag = false;
let moveDiv = document.querySelector('.mouse-style');
function touchmouse(event) {
const Ev = event.touches ? event.touches[0] : event
switch (event.type) {
case 'touchstart':
flag = true;
range.x = Ev.clientX - Ev.target.offsetLeft;
range.y = Ev.clientY - Ev.target.offsetTop;
break;
case 'mousedown':
flag = true;
range.x = Ev.clientX - Ev.target.offsetLeft;
range.y = Ev.clientY - Ev.target.offsetTop;
break;
case 'touchmove':
if (flag) {
console.log(Ev);
lastPos.x = Ev.clientX - range.x;
lastPos.y = Ev.clientY - range.y;
moveDiv.style.left = `${lastPos.x}px`;
moveDiv.style.top = `${lastPos.y}px`;
}
event.preventDefault();
break;
case 'mousemove':
if (flag) {
lastPos.x = Ev.clientX - range.x;
lastPos.y = Ev.clientY - range.y;
moveDiv.style.left = `${lastPos.x}px`;
moveDiv.style.top = `${lastPos.y}px`;
}
break;
case 'touchend':
flag = false;
break;
case 'mouseup':
flag = false;
break;
}
}
moveDiv.addEventListener('touchstart', touchmouse, false)
moveDiv.addEventListener('touchmove', touchmouse, false)
moveDiv.addEventListener('touchend', touchmouse, false)
moveDiv.addEventListener('mousedown', touchmouse, false)
moveDiv.addEventListener('mousemove', touchmouse, false)
moveDiv.addEventListener('mouseup', touchmouse, false)