0%

禁止移动端右滑触发回退 & 禁止浏览器下拉刷新

slide.gif

在移动端场景中,‘滑动’交互已经是个常见的交互。而在移动端浏览器下,对页面的滑动又有可能触发 浏览器回退/浏览器下拉刷新,影响交互结果

禁止移动端右滑触发回退

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var xPos = null;
var yPos = null;
window.addEventListener("touchmove", function (event) {
var touch = event.originalEvent.touches[0];
oldX = xPos;
oldY = yPos;
xPos = touch.pageX;
yPos = touch.pageY;
if (oldX == null && oldY == null) {
return false;
} else {
if (Math.abs(oldX - xPos) > Math.abs(oldY - yPos)) {
event.preventDefault();
return false;
}
}
});

压缩版:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var xPos = null;
var yPos = null;
window.addEventListener("touchmove", function (event) {
var touch = event.originalEvent.touches[0];
oldX = xPos;
oldY = yPos;
xPos = touch.pageX;
yPos = touch.pageY;
if (oldX == null && oldY == null) {
return false;
} else {
if (Math.abs(oldX - xPos) > Math.abs(oldY - yPos)) {
event.preventDefault();
return false;
}
}
});

禁止浏览器下拉刷新

1
2
3
4
5
html,
body {
/* Disables pull-to-refresh but allows overscroll glow effects. */
overscroll-behavior-y: contain;
}

如果样式设置不生效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
(function () {
var touchStartHandler, touchMoveHandler, touchPoint;

// Only needed for touch events on chrome.
if (
(window.chrome || navigator.userAgent.match("CriOS")) &&
"ontouchstart" in document.documentElement
) {
touchStartHandler = function () {
// Only need to handle single-touch cases
touchPoint = event.touches.length === 1 ? event.touches[0].clientY : null;
};

touchMoveHandler = function (event) {
var newTouchPoint;

// Only need to handle single-touch cases
if (event.touches.length !== 1) {
touchPoint = null;

return;
}

// We only need to defaultPrevent when scrolling up
newTouchPoint = event.touches[0].clientY;
if (newTouchPoint > touchPoint) {
event.preventDefault();
}
touchPoint = newTouchPoint;
};

document.addEventListener("touchstart", touchStartHandler, {
passive: false,
});

document.addEventListener("touchmove", touchMoveHandler, {
passive: false,
});
}
})();

参考

Disable web page navigation on swipe(back and forward)

How to prevent pull-down-to-refresh of mobile chrome

众筹开高达