先上代码:
function longPress(options) { var defauts = { selector: 'body', delay: 1000, pressEnd: function () {} } this.opts = Object.assign({}, defauts, options); this.timer = null; this.init(); } longPress.prototype.init = function () { var _this = this; var element = document.querySelectorAll(this.opts.selector); element.forEach(function(o, i, a){ // 触摸开始 element[i].addEventListener('touchstart', function(e){ _this.timer = setTimeout(function(){ _this.opts.pressEnd(e, element[i]); if (_this.timer) { clearTimeout(_this.timer); } }, _this.opts.delay); }, false); // 触摸结束 element[i].addEventListener('touchend', function(e){ if (_this.timer) { clearTimeout(_this.timer); } }, false); }); }
调用方法:
new longPress({ selector: '.banner', delay: 2000, pressEnd: function (e, ele) { console.log(e, ele); } })
解读:
主要用到touch事件中的touchstart和touchend事件,当touchstart时候开启定时器,指定延迟时间,执行操作并清掉定时器。touchend时清除定时器。