移动端长按事件

   第一种方法:这个例子我获取不到当前长按元素;

$.fn.longPress = function(fn) {
    var timeout = undefined;
    var $this = this;
    for(var i = 0;i<$this.length;i++){
        $this[i].addEventListener('touchstart', function(event) {
            timeout = setTimeout(fn, 800);  //长按时间超过800ms,则执行传入的方法
            }, false);
        $this[i].addEventListener('touchend', function(event) {
            clearTimeout(timeout);  //长按时间少于800ms,不会执行传入的方法
            }, false);
    }
}
调用:
$('.object').longPress(function(){
    //do something...
});


第二种方法:这个方法能获取到当前元素;

var timeOutEvent=0,cardId;
  $(".card-list li").on({
  touchstart: function(e){
    var that = this;
    timeOutEvent = setTimeout(function () {
      //长按触发事件
      timeOutEvent = 0;
      alert(‘我在长按');
    },800);
    // e.preventDefault();
  },
  touchmove: function(){
    clearTimeout(timeOutEvent);
    timeOutEvent = 0;
  },
  touchend: function(){
    clearTimeout(timeOutEvent);
    // return false;
  }
})



posted @ 2017-07-05 14:33  小雨晨  阅读(2505)  评论(0编辑  收藏  举报