移动端事件笔记
移动端主要的事件有:touchstart、touchmove、touchend、touchcancel、gesturestart、gesturechange、gestureend
前四者为触摸事件,后者为手势事件,其中需要注意的是touchstart -> touchmove -> touchend -> click的顺序。并且触发了touchmove事件就不会触发click事件
触摸事件的event提供了如下属性:
对于手势事件,还提供了event.scale 和 event.rotation两个特别有用的属性。
具体的使用在下面代码
<!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>