使用date()时jquery $ .on()和触摸事件处理奇怪的行为

时间:2012-09-25 22:37:58

标签: events jquery-mobile mobile-safari jquery

为了在移动设备上实现“长按”,我开始使用简单的事件地图,其中touchstart设置时间,touchend设置另一个,然后计算看看元素按下的时间有多大差异。这是我的旧代码:

        $('html')
            .on({
                touchstart : function(e){
                    g.tt.start = new Date();
                },
                touchend : function(e){
                    g.tt.end = new Date();
                    g.tt.delta = g.tt.end - g.tt.start;
                    alert(g.tt.delta);
                    g.tt = {};
                }
            })
        ;

但不幸的是......

......其他所有媒体都在计算与之前的touchend到touchstart的差异。我很确定有一些基本的东西我不知道,因此最终过度设计这个(我不担心正式的训练)。这是我的新代码:

        $('html')
            .on({
                touchstart : function(e){
                    g.tt = {};
                    g.tt.start = new Date();
                },
                touchend : function(e){
                    g.tt.end = new Date();
                    g.tt.delta = g.tt.end - g.tt.start;
                    if( isNaN(g.tt.delta) == false ) {
                        alert(g.tt.delta);
                    } 
                    else {
                        return false;
                    }
                    setTimeout(function(){g.tt = {}; });
                }
            })
        ;

使用较少的条款不应该有更简单的方法吗?别介意我有趣的g.tt变量名。

2 个答案:

答案 0 :(得分:1)

我意识到我采取了错误的方法,并且还找到了一个不错的插件:

http://aanandprasad.com/articles/jquery-tappable/

答案 1 :(得分:0)

您正在计算两个事件之间的差异,因此不需要使用setTimeout,只需使用closure来共享两个事件之间的一些变量。此示例取自此answer

(function () {
  var start, end;
  $('html').on({
    touchstart : function(e){
      start = +new Date(); // get unix-timestamp in milliseconds
    },
    touchend : function(e){
      end = +new Date();
      g.tt.delta = end - start;
      if( isNaN(g.tt.delta) == false ) {
        alert(g.tt.delta);
      }
    }
  });
})();

这是demo showing this with mouse events and touch events