当前位置: 代码迷 >> JavaScript >> 在“触摸移动”事件上,查看垂直方向拖动了多少像素
  详细解决方案

在“触摸移动”事件上,查看垂直方向拖动了多少像素

热度:10   发布时间:2023-06-05 11:59:47.0

我将touchmove事件绑定到其中具有滑块图形的div,并且需要以某种方式计算用户上下拖动的像素数,因此我可以调整滑块图形(确实不想为此使用任何库,因为它是唯一发生此功能的地方)。

所以我看起来像这样

$('div').bind('touchmove', function(e) {
  e.preventDefault();

  // See direction where users drag.
  var pix = //how many pixels draged up or down
});
$('div').on('touchstart', function(e) {
    var touchStart = e.touches[0].clientY;
    var touchDistance = 0;

    function touchMove(e) {
        touchDistance = e.touches[0].clientY - touchStart;
    }
    $(this).on('touchmove', touchMove).one('touchend', function() {
        $(this).off('touchmove', touchMove);
    });
});

一键操作!

它的工作原理是获取初始触摸位置,然后在移动手指时使用该位置获取偏移量。

您在这里必须谨慎对待事件监听器,否则最终将导致大量事件监听器和内存泄漏,因此请不要忘记在触摸结束时取消绑定touchmove事件。

如果您需要帮助,请告诉我!

  相关解决方案