1 回答
TA贡献1895条经验 获得超3个赞
好的,我认为解决方案就在那里:
我所做的是向盒子添加一个属性(如果你只有一个盒子,你可以只声明一个全局变量)来存储盒子的当前位置
const box = document.querySelector('.box');
box.addEventListener('dragstart', dragStart);
box.addEventListener("drag", handleDrag);
box.addEventListener("dragend", dragEnd);
box.currentTransform = 0; // adding this
let startX = 0;
function dragStart(e) {
startX = e.clientX;
console.log(startX);
}
function handleDrag(e) {
const currentX = e.clientX;
box.style.transform = 'translateX(' +
(box.currentTransform + currentX - startX) + // changed that
'px)';
}
function dragEnd(e) {
box.currentTransform += e.clientX - startX // added that
box.style.transform = 'translateX(' + (box.currentTransform) + 'px)'; // changed this
}
.container {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 250px;
height: 250px;
background-color: tomato;
}
<div class="container">
<div class="box" draggable="true"></div>
</div>
现在它似乎工作得很好
添加回答
举报