JS 33 - 在触控装置侦测手势的滑动方向!

大家好!

今天我们要实作在触控装置中侦测手势的方向。
我们进入今天的主题吧!
备注:前几天和今天的范例将会於近期补上。


程序码

(function (xPos, yPos, xGap, yGap, timeGap, el) {
    Felix(document).on('touchstart', start, false);
    Felix(document).on('touchmove', move, false);
    Felix(document).on('touchend', end, false);

    function start(e) {
        /* 元素没有 data-swipeable="true" 的属性时,停止事件监听器。 */
        if (e.target.dataset.swipeable !== 'true') return;
        el = e.target;
        timeGap = Date.now();
        xPos = e.touches[0].clientX;
        yPos = e.touches[0].clientY;
        xGap = 0;
        yGap = 0;
    }

    function move(e) {
        if (!xPos || !yPos) return;
        xGap = xPos - e.touches[0].clientX;
        yGap = yPos - e.touches[0].clientY;
    }

    function end(e) {
        /* 滑动到其他元素时,停止事件监听器。 */
        if (el !== e.target) return;
        
        let dir = '';
        const time = Date.now() - timeGap;
        /* 设定触发条件,预设为 10px。 */
        const condition = parseInt(el.dataset.swipeCondition || '10', 10);
        /* 设定持续条件,预设为 1s。 */
        const timeout = parseInt(el.dataset.swipeTimeout || '1000', 10);
        
        (function (x, y) {
            if (x > y) {
                if (x <= condition || time >= timeout) return;
                dir = xGap > 0 ? 'left' : 'right';
            } else {
                if (y <= condition || time >= timeout) return;
                dir = yGap > 0 ? 'up' : 'down';
            }
        })(Math.abs(xGap), Math.abs(yGap));
        
        xPos = null;
        yPos = null;
        timeGap = null;

        if (dir === '') return;
        const event = new CustomEvent(event, {
            detail: { direction: dir },
            bubbles: true,
            cancelable: true
        });
        el.dispatchEvent(event);
    }
})(null, null, null, null, null, null);

实测

范例连结制作中。


差不多也到尾声了。
如果对文章有任何疑问,也欢迎在下方提问和建议!
我是 Felix,我们明天再见!


<<:  Day33 - Windows 提权(4)-常见提权脚本

>>:  Extra03 - Browserslist - 配置专案执行目标环境

乔叔教 Elastic - 28 - Elasticsearch 的优化技巧 (2/4) - Searching 搜寻效能优化

Elasticsearch 的优化技巧 系列文章索引 (1/4) - Indexing 索引效能优化...

D13-(9/13)-鸿海(2317)-iPhone组装概念股

注:发文日和截图的日期不一定是同一天,所以价格计算上和当日不同,是很正常的。 声明:这一系列文章并无...

[机派X] Day 13 - 希望是最後一次,动手组装无人机罗

引言 今天是机派X系列文章的第十三天。 昨天终於介绍完无人机上的重要部件,从今天开始会动手组装无人机...

Youtube Analytics API 教学 - 打破地理位置的界线 'country' 维度

「鲑鱼均,因为一场鲑鱼之乱被主管称为鲑鱼世代,广义来说以年龄和脸蛋分类的话这应该算是一种 KNN 的...

Unity自主学习(十五):认识Unity介面(6)

昨天重新熟悉整个"游戏执行区"之後,就剩下两个主要的区块了 今天来看"...