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

作者:fonglezen 时间:2024-04-29 13:45:46 

本文实例讲述了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程序设计有所帮助。

标签:js,手机,pc,方法
0
投稿

猜你喜欢

  • Oracle数据库的安全策略

    2010-07-31 13:13:00
  • Python面向对象之内置函数相关知识总结

    2022-06-05 10:30:24
  • 基于Python制作flappybird游戏的详细步骤

    2023-07-29 10:08:29
  • nodejs读取并去重excel文件

    2024-04-27 16:17:48
  • 让Entity Framework支持MySql数据库

    2010-12-14 15:22:00
  • MS IIS server Frontpage Ext Server漏洞

    2008-05-04 09:54:00
  • TensorFlow实现模型评估

    2023-10-15 22:36:51
  • python使用Flask框架获取用户IP地址的方法

    2023-08-09 03:15:23
  • 跟老齐学Python之集合(set)

    2023-02-11 00:51:31
  • 情感的容器 被寄托了的QQ2010视觉设计

    2010-02-03 14:51:00
  • Response.Flush的使用心得

    2010-04-08 12:57:00
  • python3 QT5 端口转发工具两种场景分析

    2023-04-03 10:34:46
  • 一文教你如何用Python轻轻松松操作Excel,Word,CSV

    2021-11-20 22:47:52
  • 10款最好的Python开发编辑器

    2022-02-14 07:35:28
  • vue数据双向绑定的注意点

    2024-05-05 09:07:43
  • 如何去除点击链接时出现的虚线框

    2007-12-02 17:38:00
  • Python读写zip压缩文件的方法

    2021-10-08 02:28:11
  • vue实现父子组件之间的通信以及兄弟组件的通信功能示例

    2024-05-21 10:15:43
  • 如何安装并在pycharm使用selenium的方法

    2022-02-11 07:00:56
  • Mysql 命令行模式访问操作mysql数据库操作

    2024-01-14 07:43:41
  • asp之家 网络编程 m.aspxhome.com