Home  >  Article  >  Web Front-end  >  js determines the method of selecting different execution events between mobile phone and pc_javascript skills

js determines the method of selecting different execution events between mobile phone and pc_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:16:531340browse

The example in this article describes how js determines the different execution events selected by the mobile phone and PC. Share it with everyone for your reference. The details are as follows:

Judge whether it is a mobile phone:

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);
}

Determine which event to use:

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

Corresponding processing of three events:

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;
},

Block browser default event method:

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

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn