滚动时停止触摸开始执行太快

我正在试图弄清楚如何解决滚动时分配给元素的tapped类,但它生效太快了,我需要在实际触摸时稍微延迟它而不是在滚动时触摸,这是我的代码这个怎么运作:

$('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function() { var self = $(this); self.addClass(self.data('tappable-role')); }).bind('touchend', function() { var self = $(this); self.removeClass(self.data('tappable-role')); }).bind('click', function() { var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; } }); 

当滚动时,它会在我几乎没有碰到它时将类分配给元素,我想防止这种情况发生,除非它被正确触摸(没有点击)。 虽然我尝试使用setTimeout进行试验,但由于它延迟但效果不佳,但它仍会在以后分配该类。

这就是我用setTimeout做的方法:

 var currentTapped; $('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function() { clearTimeout(currentTapped); var self = $(this); var currentTapped = setTimeout(function() { self.addClass(self.data('tappable-role')); }, 60); }).bind('touchend', function() { clearTimeout(currentTapped); var self = $(this); self.removeClass(self.data('tappable-role')); }).bind('click', function() { clearTimeout(currentTapped); var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; } }); 

我怎样才能有效地做到这一点?

  • 演示#1(使用setTimeout) 。
  • 演示#2(没有setTimeout)

您需要在iPhone / iPod / iPad或模拟器上查看它以测试小提琴。

更新:

 function nextEvent() { $(this).on('touchend', function(e) { var self = $(this); self.addClass(self.data('tappable-role')).off('touchend'); }) .on('touchmove', function(e) { var self = $(this); self.removeClass(self.data('tappable-role')).off('touchend'); }) .click(function() { var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; } }); } $('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent); 

我是这样做的:

基本上,当您导航页面时,您将点击或滚动。 (还有其他的东西,比如捏和幻灯片,你可以稍后弄清楚)……

所以在点击时你的’touchstart’后面会有一个’touchend’在滚动你的’touchstart’之后会有一个’touchmove’

在其他版本上使用Jq 1.7 …你可以使用.bind()

 function nextEvent() { //behaviour for end $(this).on('touchend', function(e){ /* DO STUFF */ $(this).off('touchend'); }); //behaviour for move $(this).on('touchmove', function(e){ $(this).off('touchend'); }); } $('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent); 

基本上,当’touchstart’发生时,我将动作绑定到’touchend’和’touchmove’。

‘Touchend’会做任何我想要点击做的事情然后解除绑定’Touchmove’除了解开’touchend’之外基本上什么都不做

这样,如果你点击你得到动作,如果滚动没有任何事情发生但滚动..

回应评论:如果我理解你的评论,试试这个:

 function nextEvent() { var self = $(this); self.addClass(self.data('tappable-role')) //behaviour for move $(this).on('touchmove', function(e){ self.removeClass(self.data('tappable-role')); }); } $('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent); 

尽管这是一个已经选择了最佳答案的相对陈旧的问题,但我想分享我的解决方案。 我通过点击触发事件来实现这一目标。

 $("div, a, span").on("click", function() { // Your code here } 

也许这不是最好的方法,但这对我有用。