服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - js判断手机和pc端选择不同执行事件的方法

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

2021-07-31 17:25fonglezen JavaScript

这篇文章主要介绍了js判断手机和pc端选择不同执行事件的方法,可实现判断手机端还是PC端再选择对应的执行事件的功能,是非常实用的技巧,需要的朋友可以参考下

本文实例讲述了js判断手机和pc端选择不同执行事件的方法。分享给大家供大家参考。具体如下:

判断是否为手机:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}

判断使用那种事件:

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

三种事件的相应处理:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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;
},

阻止浏览器默认事件方法:

?
1
2
3
4
5
6
7
8
function stopDefault(e){
  var e=e || window.event;
 if(e.preventDefault){
 e.preventDefault();
 }else{
 e.returnValue=false;
 }
}

希望本文所述对大家的javascript程序设计有所帮助。

延伸 · 阅读

精彩推荐