Fork me on GitHub

移动端tap事件,消除300毫秒延迟

引用这个之前,要讲一下首先我是用了webpack技术,所以你的项目如果没有用到这个的话,最好不要用这个技术,当然想用也可以,改下代码也可以用。

下面的代码直接复制就可以用啦。

( function(element, factory) {'use strict';
element.auiTap = factory(element, element.document);
}( typeof window !== 'undefined' ? window : this, function(window, document) {'use strict';
var auiTap = function() {
this.el = window.document;
this.moved = false;
this.startX = 0;
this.startY = 0;
this.hasTouchEventOccured = false;
this.el.addEventListener('touchstart', this, false);
}
auiTap.prototype.start = function(e) {
if (e.type === 'touchstart') {
this.hasTouchEventOccured = true;
this.el.addEventListener('touchmove', this, false);
this.el.addEventListener('touchend', this, false);
this.el.addEventListener('touchcancel', this, false);
}
this.moved = false;
this.startX = e.type === 'touchstart' ? e.touches[0].clientX : e.clientX;
this.startY = e.type === 'touchstart' ? e.touches[0].clientY : e.clientY;
};

auiTap.prototype.move = function(e) {
var x = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX;
var y = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY;
if (Math.abs(x - this.startX) > 10 || Math.abs(y - this.startY) > 10) {
this.moved = true;
}
};

auiTap.prototype.end = function(e) {
var evt;
this.el.removeEventListener('touchmove', this, false);
this.el.removeEventListener('touchend', this, false);
this.el.removeEventListener('touchcancel', this, false);
if (!this.moved) {
try {
evt = new window.CustomEvent('tap', {
bubbles : true,
cancelable : true
});
} catch (e) {
evt = document.createEvent('Event');
evt.initEvent('tap', true, true);
}
e.stopPropagation();
if (!e.target.dispatchEvent(evt)) {
e.preventDefault();
}
}
};
auiTap.prototype.cancel = function() {
this.hasTouchEventOccured = false;
this.moved = false;
this.startX = 0;
this.startY = 0;
};
auiTap.prototype.destroy = function() {
this.el.removeEventListener('touchstart', this, false);
this.el.removeEventListener('touchmove', this, false);
this.el.removeEventListener('touchend', this, false);
this.el.removeEventListener('touchcancel', this, false);
};
auiTap.prototype.handleEvent = function(e) {
switch (e.type) {
case 'touchstart':
this.start(e);
break;
case 'touchmove':
this.move(e);
break;
case 'touchend':
this.end(e);
break;
case 'touchcancel':
this.cancel(e);
break;
}
};
return auiTap;
}));
module.exports = new auiTap();

posted @ 2017-07-28 17:02  广东靓仔-啊锋  阅读(1064)  评论(0编辑  收藏  举报