要实现在JavaScript中的图片触摸拖拽,你可以使用HTML5的touchstart,touchmove,和touchend事件。以下是一个简单的示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Touch Drag and Drop</title>
  <style>
    #draggable {
      width: 100px;
      height: 100px;
      background-color: lightblue;
      position: absolute;
    }
  </style>
</head>
<body>
  <div id="draggable"></div>

  <script>
    var draggable = document.getElementById('draggable');

    var offsetX, offsetY, isDragging = false;

    draggable.addEventListener('touchstart', function (e) {
      var touch = e.touches[0];
      offsetX = touch.clientX - draggable.getBoundingClientRect().left;
      offsetY = touch.clientY - draggable.getBoundingClientRect().top;
      isDragging = true;
    });

    draggable.addEventListener('touchmove', function (e) {
      if (!isDragging) return;

      e.preventDefault();

      var touch = e.touches[0];
      var x = touch.clientX - offsetX;
      var y = touch.clientY - offsetY;

      // 限制拖拽范围,确保不超出屏幕边界
      x = Math.max(0, Math.min(x, window.innerWidth - draggable.offsetWidth));
      y = Math.max(0, Math.min(y, window.innerHeight - draggable.offsetHeight));

      draggable.style.left = x + 'px';
      draggable.style.top = y + 'px';
    });

    draggable.addEventListener('touchend', function () {
      isDragging = false;
    });
  </script>
</body>
</html>

在这个例子中,我们有一个可拖动的

元素,当用户触摸屏幕时,会触发touchstart事件,记录当前触摸点与元素左上角的偏移量。然后,在touchmove事件中,我们根据触摸点的位置更新元素的位置。最后,在touchend事件中,我们标记拖拽结束。这样,用户就可以通过触摸屏幕来拖拽图片。

版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/image-touch-drag-and-drop.html
本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!