WKWebView - prevent automatic scrolling triggered by user text selection

后端 未结 1 1076
栀梦
栀梦 2021-01-12 02:19

When a user performs a tap and hold gesture to select a word and then drags their finger towards either the top or bottom edges of the screen, the page automatically scrolls

1条回答
  •  醉话见心
    2021-01-12 02:43

    I ended up solving this problem by saving the last scroll position and scrolling to it when appropriate, like so:

    var shouldAllowScrolling = true;
    var lastSavedScrollLeft = 0;
    var lastSavedScrollTop = 0;
    
    function saveScrollPosition() {
        lastSavedScrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
        lastSavedScrollTop = window.pageYOffset || document.documentElement.scrollTop;
    }
    
    document.addEventListener('touchstart', e => {
        saveScrollPosition();
    });
    
    document.addEventListener('touchend', () => {
        // enable scrolling when the user lifts their finger, to allow scrolling while text selection is still present
        shouldAllowScrolling = true;
    });
    
    document.addEventListener('scroll', e => {
        if (!shouldAllowScrolling) {
            window.scrollTo(lastSavedScrollLeft, lastSavedScrollTop);
        }
    });
    
    document.addEventListener('selectionchange', e => {
        shouldAllowScrolling = getSelectedText().length === 0;
    });
    

    If someone can offer a more elegant solution that prevents the scrolling entirely ill be happy to accept it.

    EDIT:

    this solution may cause light shaking/jittering.

    that can be solved by performing the scroll natively through the WKWebView as opposed to calling window.scrollTo() in the javascript.

    0 讨论(0)
提交回复
热议问题