zoukankan      html  css  js  c++  java
  • 移动端原生js使用touch事件监听滑动方向

    let box = document.querySelector('body') // 监听对象
            let startTime = '' // 触摸开始时间
            let startDistanceX = '' // 触摸开始X轴位置
            let startDistanceY = '' // 触摸开始Y轴位置
            let endTime = '' // 触摸结束时间
            let endDistanceX = '' // 触摸结束X轴位置
            let endDistanceY = '' // 触摸结束Y轴位置
            let moveTime = '' // 触摸时间
            let moveDistanceX = '' // 触摸移动X轴距离
            let moveDistanceY = '' // 触摸移动Y轴距离
            box.addEventListener("touchstart", (e) => {
                startTime = new Date().getTime()
                startDistanceX = e.touches[0].screenX
                startDistanceY = e.touches[0].screenY
            })
            box.addEventListener("touchend", (e) => {
                endTime = new Date().getTime()
                endDistanceX = e.changedTouches[0].screenX
                endDistanceY = e.changedTouches[0].screenY
                moveTime = endTime - startTime
                moveDistanceX = startDistanceX - endDistanceX
                moveDistanceY = startDistanceY - endDistanceY
                console.log(moveDistanceX, moveDistanceY)
                // 判断滑动距离超过40 且 时间小于500毫秒
                if ((Math.abs(moveDistanceX) > 40 || Math.abs(moveDistanceY) > 40) && moveTime < 500) {
                    // 判断X轴移动的距离是否大于Y轴移动的距离
                    if (Math.abs(moveDistanceX) > Math.abs(moveDistanceY)) {
                        // 左右
                        console.log(moveDistanceX > 0 ? '' : '')
                    } else {
                        // 上下
                        console.log(moveDistanceY > 0 ? '' : '')
                    }
                }
            })

    原著地址:https://www.jb51.net/article/214885.htm

  • 相关阅读:
    11.枚举类.md
    10. Lambda表达式.md
    9.内部类
    8.抽象类、接口和多态.md
    7.final关键字.md
    jQuery学习笔记(5)-事件与事件对象
    Log4Net学习笔记(1)-完整的例子
    SqlServer知识点-操作xml
    NHibernate常见错误汇总(0)-持续更新中
    jQuery学习笔记(4)-设置元素的属性和样式
  • 原文地址:https://www.cnblogs.com/liangziaha/p/15253382.html
Copyright © 2011-2022 走看看