移動端主要的事件有:touchstart、touchmove、touchend、touchcancel、gesturestart、gesturechange、gestureendhtml
前四者爲觸摸事件,後者爲手勢事件,其中須要注意的是touchstart -> touchmove -> touchend -> click的順序。而且觸發了touchmove事件就不會觸發click事件web
觸摸事件的event提供了以下屬性:canvas
對於手勢事件,還提供了event.scale 和 event.rotation兩個特別有用的屬性。app
具體的使用在下面代碼ui
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="format-detection"content="telephone=no, email=no" /> <title>Mobile touch event</title> <style> html,body,#canvas{ width: 100%; height: 100%; padding: 0; margin: 0; } #canvas{ position: relative; background-color: #ccc; } .spirit{ position: absolute; background-color: #f30; display: block; } </style> </head> <body> <div id="canvas"></div> <script> var canvas = document.getElementById('canvas'),spirit,startScale,startRotation; var touchstartFun = function(e){ e.preventDefault(); if(!spirit && e.touches.length >1){ var sPoint = e.touches[0]; var ePoint = e.touches[1]; spirit = document.createElement('div') ; spirit.className = 'spirit'; spirit.style.left = Math.min(sPoint.pageX,ePoint.pageX) + 'px'; spirit.style.top = Math.min(sPoint.pageY,ePoint.pageY) + 'px'; spirit.style.width = Math.abs(sPoint.pageX - ePoint.pageX) + 'px'; spirit.style.height = Math.abs(sPoint.pageY - ePoint.pageY) + 'px'; canvas.appendChild(spirit); } }; var gesturestartFun = function(e){ e.preventDefault(); }; var gesturechangestureendFun = function(e){ e.preventDefault(); if(startRotation == null || startScale == null){ startScale = 0; startRotation = 0; }else{ spirit.style.webkitTransform = 'scale('+ (e.scale + startScale) +') rotate('+ (e.rotation + startRotation) +'deg)' } }; var gestureendFun = function(e){ e.preventDefault(); canvas.removeChild(spirit); spirit = null; startScale = null; startRotation = null; }; //必須填false,不填寫默認應該也是false,可是手機端必須填false! canvas.addEventListener('touchstart',touchstartFun,false); canvas.addEventListener('gesturestart',gesturestartFun,false); canvas.addEventListener('gesturechange',gesturechangestureendFun,false); canvas.addEventListener('gestureend',gestureendFun,false); var orientationchangestureendFun = function(){ switch(window.orientation) { case 0: alert("肖像模式 0,screen-width: " + screen.width + "; screen-height:" + screen.height); break; case -90: alert("左旋 -90,screen-width: " + screen.width + "; screen-height:" + screen.height); break; case 90: alert("右旋 90,screen-width: " + screen.width + "; screen-height:" + screen.height); break; case 180: alert("風景模式 180,screen-width: " + screen.width + "; screen-height:" + screen.height); break; }; }; //window.addEventListener('orientationchange',orientationchangestureendFun,false); window.onorientationchange = orientationchangestureendFun; </script> </body> </html>