首页 > 语言 > JavaScript > 正文

js移动端事件基础及常用事件库详解

2024-05-06 15:12:54
字体:
来源:转载
供稿:网友

一、事件基础

PC:click、mouseover、mouseout、mouseenter、mouseleave、mousemove、mousedown、mouseup、mousewheel、keydown、keyup、load、scroll、blur、focus、change...

移动端:click(单击)、load、scroll、blur、focus、change、input(代替keyup、keydown)...TOUCH事件模型(处理单手指操作)、GESTURE事件模型(处理多手指操作)

TOUCH:touchstart、touchmove、touchend、touchcancel

GESTURE:gesturestart、gesturechange、gestureend

1、click:在移动端click属于单击事件,不是点击事件,在移动端的项目中我们经常会区分单击做什么和双击做什么,所以移动端的浏览器在识别click的时候,只有确定是单击后才会把它执行:

在移动端使用click会存在300ms的延迟:浏览器在第一次点击结束后,还需要等到300ms看是否触发了第二次点击,如果触发了第二次点击就不属于click了,没有触发第二次点击才属于click

下面代码是移动端模拟click时间的代码

function on(curEle,type,fn){   curEle.addEventListener(type,fn,false);  }  var oBox = document.querySelector('.box');  //移动端采用click存在300ms延迟  // oBox.addEventListener('click',function(){  //  this.style.webkitTransform = 'rotate(360deg)'  // },false)  //使用TOUCH事件模型实现点击操作(单击&&双击)  on(oBox,'touchstart',function(ev){   //ev:TouchEvent事件 属性 type、target、preventDefault(returnValue)、stopPropagation、changedTouches、touches   //changedTouches和touches都是手指信息的集合(touchList),touches获取到值的必要条件只有手指还在屏幕上才可以获取,所以在touchend事件中如果想获取手指离开的瞬间坐标只能使用changedTouches获取   var point = ev.touches[0];   this['strX'] = point.clientX;   this['strY'] = point.clientY;   this['isMove'] = false;  })  on(oBox,'touchmove',function(ev){   var point = ev.touches[0];   var newX = point.clientX,    newY = point.clientY;   //判断是否发生滑动,我们需要判断偏移的值是否在30PX以内   if(Math.abs(newX-this['strX'])>30 || Math.abs(newY-this['strY'])>30){    this['isMove'] = true;   }  })  on(oBox,'touchend',function(ev){   if(this['isMove'] === false){    //没有发生移动 点击    this.style.webkitTransitionDuration = '1s';    this.style.webkitTransform = 'rotate(360deg)';    var delayTimer = window.setTimeout(function(){     this.style.webkitTransitionDuration = '0s';     this.style.webkitTransform = 'rotate(0deg)';    }.bind(this),1000);   }else{    //滑动    this.style.background = 'red';   }  })

同时也可以使用fastclick.js来解决移动端click事件的300ms延迟 (github地址https://github.com/zhouxiaotian/fastclick)

2、点击、单击、双击、长按、滑动、左滑、右滑、上滑、下滑

单击和双击(300MS)

点击和长按(750MS)

点击和滑动(X/Y轴偏移的距离是否在30PX以内,超过30PX就是滑动)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选