iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

后端 未结 14 1577
南方客
南方客 2020-11-28 17:50

I\'m working on an iPad-based web app, and need to prevent overscrolling so that it seems less like a web page. I\'m currently using this to freeze the viewport and disable

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 18:16

    This solves the issue when you scroll past the beginning or end of the div

    var selScrollable = '.scrollable';
    // Uses document because document will be topmost level in bubbling
    $(document).on('touchmove',function(e){
      e.preventDefault();
    });
    // Uses body because jQuery on events are called off of the element they are
    // added to, so bubbling would not work if we used document instead.
    $('body').on('touchstart', selScrollable, function(e) {
      if (e.currentTarget.scrollTop === 0) {
        e.currentTarget.scrollTop = 1;
      } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
        e.currentTarget.scrollTop -= 1;
      }
    });
    // Stops preventDefault from being called on document if it sees a scrollable div
    $('body').on('touchmove', selScrollable, function(e) {
      e.stopPropagation();
    });
    

    Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):

    $('body').on('touchmove', selScrollable, function(e) {
        // Only block default if internal div contents are large enough to scroll
        // Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
        if($(this)[0].scrollHeight > $(this).innerHeight()) {
            e.stopPropagation();
        }
    });
    

提交回复
热议问题