JS 长按事件

$.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 self = this;
var longClick =0;
$(".product").on({
    touchstart: function(e){
        longClick=0;//设置初始为0
        timeOutEvent = setTimeout(function(){
            //此处为长按事件-----在此显示遮罩层及删除按钮
            longClick=1;//假如长按,则设置为1
        },500);
    },
    touchmove: function(){
        clearTimeout(timeOutEvent);
        timeOutEvent = 0;
        e.preventDefault();
    },
    touchend: function(e){
        clearTimeout(timeOutEvent);
        if(timeOutEvent!=0 && longClick==0){//点击
            //此处为点击事件----在此处添加跳转详情页
        }
        return false;
    }
});

 

posted on 2019-07-10 18:30  Ben丶大壮  阅读(1241)  评论(0编辑  收藏  举报

导航