Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移动端tap事件 #24

Open
xxxgitone opened this issue Mar 21, 2018 · 0 comments
Open

移动端tap事件 #24

xxxgitone opened this issue Mar 21, 2018 · 0 comments

Comments

@xxxgitone
Copy link
Owner

在移动端中提倡使用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)
    })
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant