1. 程式人生 > >Javascript監聽觸控事件

Javascript監聽觸控事件

touchstart
在觸控開始時觸發事件
touchend
在觸控結束時觸發事件
touchmove
在觸控期間時觸發事件
整個觸控其實經歷了這麼一個過程

touchstart -> touchmove ->touchmove -> … -> touchmove ->touchend

利用touchstart和touchend觸控前後監聽到的四個座標分別是觸控前x,y座標和觸控後x,y座標,然後用數學公式進行運算得出方向

document.getElementsByTagName('body')[0].addEventListener('touchstart', function(e) {
                touch.startY = e.targetTouches[0].pageY;
                touch.startX = e.targetTouches[0].pageX;
                //console.log("點選時的X座標" + nStartX + "和Y座標" + nStartY);
            });

document.getElementsByTagName('body')[0].addEventListener('touchmove', function(e) {
                touch.whenChangY = e.changedTouches[0].pageY;
                touch.whenChangX = e.changedTouches[0].pageX;
                //console.log("滑動時的X座標" + nWhenChangX + "和Y座標" + nWhenChangY);
            })
document.getElementsByTagName('body')[0].addEventListener('touchend', function(e) {
				touch.changY = e.changedTouches[0].pageY;
				touch.changX = e.changedTouches[0].pageX;
				//console.log("滑動後的X座標" + nChangX + "和Y座標" + nChangY);
				var swDirection = direction(touch.startX, touch.changX, touch.startY, touch.changY);