在iOS全屏Web应用中禁用橡皮筋效果

8

我有一个在iOS上运行的全屏Web应用程序。当我向下滑动时,屏幕会带有橡皮筋效果(弹跳)。我想锁定整个文档,但仍允许需要的地方滚动带有overflow-y:scroll的div元素。

我已经尝试过

document.ontouchmove = function(e){ 
    e.preventDefault(); 
}

但是这会禁用任何容器中的滚动。有什么想法吗?非常感谢。
1个回答

9

在事件上调用preventDefault是正确的,但你不想对每个组件都这样做,因为这也会防止div滚动(如你所提到的)以及例如范围输入上的滑动。因此,你需要在ontouchmove处理程序中添加一个检查,看看你是否正在触摸允许滚动的组件。

我有一个实现使用CSS类的检测。我想要允许触摸移动的组件只需分配该类即可。

document.ontouchmove = function (event) {
    var isTouchMoveAllowed = false;
    var p = event.target;

    while (p != null) {
        if (p.classList && p.classList.contains("touchMoveAllowed")) {
            isTouchMoveAllowed = true;
            break;
        }
        p = p.parentNode;
    }

    if (!isTouchMoveAllowed) {
        event.preventDefault();
    }

});

1
有没有一种方法可以反过来做?即允许在没有该类的任何元素上滚动? - cbmtrx
`var isTouchMoveAllowed = true;if (p.classList && !p.classList.contains("touchMoveAllowed")) { isTouchMoveAllowed = true;` - Mattia Astorino

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接