1、Touch事件简介
pc上的web页面鼠 标会产生onmousedown、onmouseup、onmouseout、onmouseover、onmousemove的事件,但是在移动终端如 iphone、ipod Touch、ipad上的web页面触屏时会产生ontouchstart、ontouchmove、ontouchend、ontouchcancel 事件,分别对应了触屏开始、拖拽及完成触屏事件和取消。
当按下手指时,触发ontouchstart;
当移动手指时,触发ontouchmove;
当移走手指时,触发ontouchend。
当一些更高级别的事件发生的时候(如电话接入或者弹出信息)会取消当前的touch操作,即触发ontouchcancel。一般会在ontouchcancel时暂停游戏、存档等操作。
2、Touch事件与Mouse事件的出发关系
在触屏操作后,手指提起的一刹那(即发生ontouchend后),系统会判断接收到事件的element的内容是否被改变,如果内容被改变,接下来的事 件都不会触发,如果没有改变,会按照mousedown,mouseup,click的顺序触发事件。特别需要提到的是,只有再触发一个触屏事件时,才会 触发上一个事件的mouseout事件。
3、ontouchstart 事件如何定义?长按事件呢?
details:
onclick事件有一定延迟,听说ontouchstart事件更快,问题是div input等标签后面输入on时自动提示所有事件,但没有ontouchstart 事件,直接输写ontouchstart="touchstartfn(();"会导致页面操作不正常,如何定义ontouchstart事件?另外长按事件如何定义?
function noClickDelay(el) {
this.element = typeof el == 'object' ? el: document.getElementById(el);
if (window.Touch) this.element.addEventListener('touchstart', this, false);
}
NoClickDelay.prototype = {
handleEvent: function(e) {
switch (e.type) {
case 'touchstart':
this.onTouchStart(e);
break;
case 'touchmove':
this.onTouchMove(e);
break;
case 'touchend':
this.onTouchEnd(e);
break;
}
},
onTouchStart: function(e) {
e.preventDefault(); this.moved = false;
this.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
if (this.theTarget.nodeType == 3) this.theTarget = theTarget.parentNode;
this.theTarget.className += ' pressed';
this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false);
},
onTouchMove: function(e) {
this.moved = true;
this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, '');
},
onTouchEnd: function(e) {
this.element.removeEventListener('touchmove', this, false);
this.element.removeEventListener('touchend', this, false);
if (!this.moved && this.theTarget) {
this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, '');
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
this.theTarget.dispatchEvent(theEvent);
}
this.theTarget = undefined;
}
};
//使用
noClickDelay(document.getElementById('element'));



