learningProcess icon indicating copy to clipboard operation
learningProcess copied to clipboard

移动端tap事件

Open shimuash opened this issue 7 years ago • 0 comments

在移动端中提倡使用tap事件来代替click事件,因为在移动端中click事件有300ms的延迟,会导致用户体验很不好.

移动端两次触摸会使得页面缩放,所以当用户点击一次后,会有300ms间隔时间,在此时间内没有执行第二次点击,浏览器才会执行点击事件.

很多库可以处理此问题:比如fastclick,zepto

自己也可以简单封装tap事件,利用touchstarttouchmove以及touchend,原理也很简单,看代码一目了然

function tap (ele, cb) {
    var startTime = 0
    var isMove = false
    var maxTime = 250
    ele.addEventListener('touchstart', function (e) {
      startTime = Date.now()
      isMove = false
    })
    ele.addEventListener('touchmove', function (e) {
      isMove = true
    })
    ele.addEventListener('touchend', function (e) {
      if (isMove) {
        return
      }
      if ((Date.now() - startTime) > maxTime) { // 如果大于250ms才触发end事件,则认为是长按事件
        return
      }
      cb(e)
    })
  }

shimuash avatar Mar 21 '18 02:03 shimuash