如何拖动和变换一个盒子?

我正在创建一个框,我可以在其中沿页面的 X 轴拖动它。我想把它拖放到任何地方。但是,代码无法运行,因为e.clientX在新的点击后值会自行重置。因此我可以拖动它,但是当我再次拖动它时,它会自动到中间。


const box = document.querySelector('.box');

box.addEventListener('dragstart', dragStart);

box.addEventListener("drag", handleDrag);

box.addEventListener("dragend", dragEnd);

let startX = 0;


function dragStart(e) {

  startX = e.clientX;

  console.log(startX);

}


function handleDrag(e) {

  const currentX = e.clientX;

  box.style.transform = 'translateX(' + (currentX - startX) + 'px)';

}


function dragEnd(e) {

  box.style.transform = 'translateX(' + (e.clientX - startX) + 'px)';

}

.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>


守着一只汪
浏览 88回答 1
1回答

蛊毒传说

好的,我认为解决方案就在那里:我所做的是向盒子添加一个属性(如果你只有一个盒子,你可以只声明一个全局变量)来存储盒子的当前位置const box = document.querySelector('.box');box.addEventListener('dragstart', dragStart);box.addEventListener("drag", handleDrag);box.addEventListener("dragend", dragEnd);box.currentTransform = 0; // adding this&nbsp;let startX = 0;function dragStart(e) {&nbsp; startX = e.clientX;&nbsp; console.log(startX);}function handleDrag(e) {&nbsp; const currentX = e.clientX;&nbsp; box.style.transform = 'translateX(' +&nbsp;&nbsp; &nbsp; (box.currentTransform + currentX - startX) + // changed that&nbsp; &nbsp; 'px)';&nbsp;}function dragEnd(e) {&nbsp; box.currentTransform += e.clientX - startX // added that&nbsp; box.style.transform = 'translateX(' + (box.currentTransform) + 'px)'; // changed this}.container {&nbsp; width: 100vw;&nbsp; height: 100vh;&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; align-items: center;}.box {&nbsp; width: 250px;&nbsp; height: 250px;&nbsp; background-color: tomato;}<div class="container">&nbsp; <div class="box" draggable="true"></div></div>现在它似乎工作得很好
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript