在 iOS 5 上 document.ontouchmove 和滚动

2022-01-14 00:00:00 scroll javascript ios5

iOS 5 为 JavaScript/Web 应用程序带来了许多好东西.其中之一是改进的滚动.如果你添加

iOS 5 has brought a number of nice things to JavaScript/Web Apps. One of them is improved scrolling. If you add

-webkit-overflow-scroll:touch;

对于 textarea 元素的样式,用一根手指就可以很好地滚动.

to the style of a textarea element, scrolling will work nicely with one finger.

但是有一个问题.为了防止整个屏幕滚动,建议web应用添加这行代码:

But there's a problem. To prevent the entire screen from scrolling, it is recommended that web apps add this line of code:

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

但是,这会禁用新的滚动.

This, however, disables the new scrolling.

有没有人有一个很好的方法来允许在文本区域内进行新的滚动,但不允许整个表单滚动?

Does anyone have a nice way to allow the new scrolling within a textarea, but not allow the whole form to scroll?

推荐答案

更新根据 Alvaro 的评论,此解决方案可能不再适用于 iOS 11.3.

Update Per Alvaro's comment, this solution may no longer work as of iOS 11.3.

您应该能够通过选择是否调用 preventDefault 来允许滚动.例如,

You should be able to allow scrolling by selecting whether or not preventDefault is called. E.g.,

document.ontouchmove = function(e) {
    var target = e.currentTarget;
    while(target) {
        if(checkIfElementShouldScroll(target))
            return;
        target = target.parentNode;
    }

    e.preventDefault();
};

或者,这可以通过阻止事件到达文档级别来实现.

Alternatively, this may work by preventing the event from reaching the document level.

elementYouWantToScroll.ontouchmove = function(e) {
    e.stopPropagation();
};

编辑对于以后阅读的任何人来说,备用答案确实有效并且更容易.

Edit For anyone reading later, the alternate answer does work and is way easier.

相关文章