iT邦幫忙

2021 iThome 鐵人賽

1
Modern Web

JavaScript 從 50% 開始,打造函式庫不是問題!系列 第 33

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,我們明天再見!


上一篇
JS 32 - 資料丟進來,就能計算所需樣本數量!
下一篇
JS 34 - 實作 Medium 的漸進式圖片載入效果
系列文
JavaScript 從 50% 開始,打造函式庫不是問題!46
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言