大家好!
今天我们要实作在触控装置中侦测手势的方向。
我们进入今天的主题吧!
备注:前几天和今天的范例将会於近期补上。
程序码
(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,我们明天再见!