iOS 10 Safari: Prevent scrolling behind a fixed overlay and maintain scroll position

前端 未结 10 2162
我寻月下人不归
我寻月下人不归 2020-12-12 13:51

I\'m not able to prevent the main body content from scrolling while a fixed position overlay is showing. Similar questions have been asked many times, but all of the techniq

10条回答
  •  天命终不由人
    2020-12-12 14:41

    I found the code on github. It work on Safari in iOS 10,11,12

    /* ScrollClass */
    class ScrollClass {
    constructor () {
        this.$body = $('body');
    
        this.styles = {
            disabled: {
                'height': '100%',
                'overflow': 'hidden',
            },
    
            enabled: {
                'height': '',
                'overflow': '',
            }
        };
    }
    
    disable ($element = $(window)) {
        let disabled = false;
        let scrollTop = window.pageYOffset;
    
        $element
            .on('scroll.disablescroll', (event) => {
                event.preventDefault();
    
                this.$body.css(this.styles.disabled);
    
                window.scrollTo(0, scrollTop);
                return false;
            })
            .on('touchstart.disablescroll', () => {
                disabled = true;
            })
            .on('touchmove.disablescroll', (event) => {
                if (disabled) {
                    event.preventDefault();
                }
            })
            .on('touchend.disablescroll', () => {
                disabled = false;
            });
    }
    
    enable ($element = $(window)) {
        $element.off('.disablescroll');
    
        this.$body.css(this.styles.enabled);
    }
    }
    

    use:

    Scroll = new ScrollClass();
    
    Scroll.disable();// disable scroll for $(window)
    
    Scroll.disable($('element'));// disable scroll for $('element')
    
    Scroll.enable();// enable scroll for $(window)
    
    Scroll.enable($('element'));// enable scroll for $('element')
    

    I hope it helps you.

提交回复
热议问题