使用 jQuery 触摸事件捕获滑动事件 (Ben Major)

Capture swipe event with jQuery Touch Events (Ben Major)

我对这个小插件非常满意:https://github.com/benmajor/jQuery-Touch-Events。但是文档不多。我想限制用户滑动,并认为使用返回的 'swipeend' 时间值应该很容易。我不知道如何获取值!

作者的示例代码效果很好(如下),但我一定已经尝试了 100 种不同的排列,但仍然无法仅获取滑动的时间戳。我需要这个,因为没有必要限制正常的点击和滚动。

// works
$('element').on('tapend', function (e, touch) { console.log( 'tapend', touch.time ); })

// doesn't work
$('element').on('swipeend', function (e, touch) { console.log( 'swipeend', touch.time ); }) // undefined

有人可以帮我吗?

事实证明这很容易(在我阅读文档时伤透了脑筋之后。)

$( '#one' )
    .on( 'swiperight', function(){
        $( this ).addClass( 'moveright' );
    })
    .on( 'swipeleft', function(){
        $( this ).addClass( 'moveleft' );
    })
    .on( 'swipeup', function( ev, touch ){
        $( this ).removeClass( 'moveleft moveright' );
    })
    .swipeend(function( ev, touch ){  // <=== returns touch event data
        console.log( ev, ev.timeStamp ); 
    });
#one {
  width: 150px;
  height: 150px;
  background: blue;
  transition: all .4s ease-in-out;
  cursor: pointer;
 }
 #one.moveright {
   transform: translateX( 150% );
   background: red;
 }
 #one.moveleft {
   transform: translate( 50%, 50% );
   background: yellow;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-touch-events/1.0.5/jquery.mobile-events.js"></script>
<div id="one"></div>
<p>Swipe right, left and up</p>

如果您要构建复杂的事件,返回的 potential data 数量是令人难以置信的。为了进行充分的时间比较,我从 Date.now() 中减去返回的数字。显然这在 Firefox 或 IE8 中不能正常工作,但我不太关心发现解决方法。

当然,还有其他方法可以实现简单的事件限制。在大多数情况下,可以使用 .off() and set a timeout 删除处理程序,然后再将它们添加回去。