Conditionally block scrolling/touchmove event in mobile safari

后端 未结 6 1554
暗喜
暗喜 2021-02-03 13:46

iOS 5 now allows native overflow: scroll support.

What I\'d like to do is disable the touchmove event for everything except elements that have the \'scrolla

6条回答
  •  你的背包
    2021-02-03 14:06

    JavaScript version based on Nevirs answer:

    var initialY = null;
    var nodeStack = [];
    var $window = $(window);
    
    $window.bind('touchstart', function(e) {
        initialY = e.originalEvent.pageY;
        nodeStack = $(e.target).parents().andSelf().filter(':not(body, html)').get().reverse();
        nodeStack = nodeStack.map(function(node) {
            return $(node);
        });
    });
    
    $window.bind('touchend touchcancel', function(e) {
        initialY = null;
        nodeStack = [];
    });
    
    $window.bind('touchmove', function(e) {
    
        if (!initialY) {
            e.preventDefault();
        }
    
        var direction = e.originalEvent.pageY - initialY;
    
        for (var i = 0; i < nodeStack.length; i +=1) {
            var $node = nodeStack[i];
            var nodeHeight = $node.height();
            var scrollHeight = $node[0].scrollHeight - 2;
            var nodeScrollTop = $node.scrollTop();
    
            if (scrollHeight > nodeHeight) {
                // the user is dragging the content up, and the element is already scrolled down a bit.
                var allowedUp = direction > 0 && nodeScrollTop > 0;
    
                // the user is dragging the content down, and the element is up a bit.
                var allowedDown = direction < 0 && nodeScrollTop < scrollHeight - nodeHeight;
    
                if (allowedUp || allowedDown) {
                    return;
                }
            }
        }
    
        // disable drag
        e.preventDefault();
    });
    

提交回复
热议问题