>  기사  >  웹 프론트엔드  >  js는 휴대폰과 pc_javascript 기술 간의 서로 다른 실행 이벤트를 선택하는 방법을 결정합니다.

js는 휴대폰과 pc_javascript 기술 간의 서로 다른 실행 이벤트를 선택하는 방법을 결정합니다.

WBOY
WBOY원래의
2016-05-16 16:16:531341검색

이 기사의 예에서는 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 프로그래밍 설계에 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.