第一種方法:這個例子我獲取不到當前長按元素;
$.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;
}
})