DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js判斷手機和pc端選擇不同執行事件的方法
js判斷手機和pc端選擇不同執行事件的方法
編輯:關於JavaScript     

本文實例講述了js判斷手機和pc端選擇不同執行事件的方法。分享給大家供大家參考。具體如下:

判斷是否為手機:

function isMobile(){
 var sUserAgent= navigator.userAgent.toLowerCase(),
 bIsIpad= sUserAgent.match(/ipad/i) == "ipad",
 bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os",
 bIsMidp= sUserAgent.match(/midp/i) == "midp",
 bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
 bIsUc= sUserAgent.match(/ucweb/i) == "ucweb",
 bIsAndroid= sUserAgent.match(/android/i) == "android",
 bIsCE= sUserAgent.match(/windows ce/i) == "windows ce",
 bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile",
 bIsWebview = sUserAgent.match(/webview/i) == "webview";
 return (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM);
}

判斷使用那種事件:

var touchStart,touchMove,touchEnd;
touchStart = isMobile() ? 'touchstart' : 'mousedown';
touchMove = isMobile() ? 'touchmove' : 'mousemove';
touchEnd = isMobile() ? 'touchend' : 'mouseup';

三種事件的相應處理:

touchstart:function(e){
 var e=e || window.event; //要判斷使用哪種event
 stopDefault(e);     //不同的浏覽器,阻止浏覽器默認事件方法不同
 
 if(isMobile()){     //如果是手機
  var touch=e.touches[0];
  this.y1=touch.pageY
 }else{
  this.y1=e.pageY;   //如果不是手機
 }
 this.y2=0;
 },
 touchmove:function(e){
 var e=e || window.event;
 stopDefault(e);
 if(isMobile()){
  var touch=e.touches[0];
  this.y2=touch.pageY;
 }else{
  this.y2=e.pageY;
 }
 },

 touchend:function(e){
 var e=e || window.event;
 stopDefault(e);
 if(this.y2==0){
  return;
 }
 var diffY=this.y2-this.y1;
 if(diffY>50){
  this.doNext();
 }else if(diffY<-50){
  this.doPrev();
 }
 this.y1=0,
 this.y2=0;
},

阻止浏覽器默認事件方法:

function stopDefault(e){
  var e=e || window.event;
 if(e.preventDefault){
 e.preventDefault();
 }else{
 e.returnValue=false;
 }
}

希望本文所述對大家的javascript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved