第一种方法:这个例子我获取不到当前长按元素;
$.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;
}
})