css 如何在touchmove事件中移动一个居中的元素使其与绝对位置保持一致?

t98cgbkg  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(124)

我不知道如何在每次滑动的时候在内存中保存元素的坐标。这很难做到,因为元素是绝对定位和居中的。有没有办法得到当前的el坐标?
这是一个exhere in Codepen

const swipeDiv = document.querySelector(".swipe");
// console.log(swipeDiv.getBoundingClientRect().x);

swipeDiv.addEventListener("touchstart", handleTouchStart);
swipeDiv.addEventListener("touchmove", handleTouchMove);

let x1 = null;
let y1 = null;
let x2 = null;
let y2 = null;

function handleTouchStart(event) {
  const firstTouch = event.touches[0];
  if (x1 === null || y1 === null) {
    x1 = firstTouch.clientX;
    y1 = firstTouch.clientY;
  }
}

function handleTouchMove(event) {
  event.preventDefault();
  if (x1 === null || y1 === null) return false;
  window.scrollTo(window.pageXOffset, window.pageYOffset);
  x2 = event.touches[0].clientX;
  y2 = event.touches[0].clientY;
  let xDiff = x2 - x1;
  let yDiff = y2 - y1;

  this.style.transform = `translate(${-this.clientWidth / 2 + xDiff}px, ${
    -this.clientHeight / 2 + yDiff
  }px) rotate(-20deg)`;

  x1 = `${-this.clientWidth/2 + xDiff}`;
  y1 = `${-this.clientHeight/2 + yDiff}`;
}
body {
  width: 100vw;
  height: 200vh;
  margin: 0;
  pading: 0;
  display: flex;
  justify-content: center;
  font-size: 1.2rem;
  background: pink;
}

.wrapper {
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 150px;
  margin-top: 200px;
  background: #ccc;
}

.swipe {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-20deg);
  display: flex;
  justify-content: center;
  align-items: center;
  width: 400px;
  height: 300px;
  background: rgba(255, 0, 0, .5);
}
<div class="wrapper">
  <div class="swipe">Testing touchmove</div>
</div>

我试过了,但是失败了。谢谢。

zbq4xfa0

zbq4xfa01#

一种方法是在handleTouchStart中用x1减去xDiff,用y1减去yDiff,但要确保先将它们全局初始化为0,这样我们才能使用它们,如下所示:

function handleTouchStart(event) {
  const firstTouch = event.touches[0];
  x1 = firstTouch.clientX - xDiff;
  y1 = firstTouch.clientY - yDiff;
}

示例:https://codepen.io/Dodekus/pen/xxJoWoQ

相关问题