菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
259
0

js判断手机和pc端选择不同执行事件的方法

原创
05/13 14:22
阅读数 98021

判断是否为手机:

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 || bwww.cppcns.comIsCE || 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;http://www.cppcns.com
 }
 var diffY=thiswww.cppcns.com.y2-this.y1;
 if(diffY>50){
  th编程客栈is.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程序设计有所帮助。

本文标题: js判断手机和pc端选择不同执行事件的方法
本文地址: http://www.cppcns.com/wangluo/javascript/119189.html

发表评论

0/200
259 点赞
0 评论
收藏
为你推荐 换一批