Two solutions of rolling penetration

Keywords: Javascript Mobile github

Scroll through: the page slides out of a pop-up window. When we touch the screen with our fingers, we will find that the content under the pop-up window is still scrolling.

Scenario 1:

The first way to find out is to add a class (generally the body element) to the overflow: scroll: element when the pop-up window is triggered. Remove this class when exiting. For convenience, the body element will be used to refer to the element below the pop-up window.

// Part css
modal_open {
    position: fixed;
    height: 100%;
}

// Part js
document.body.classList.add('modal_open');
document.body.classList.remove('modal_open');

The above method can solve the problem of rolling penetration, but it will also bring new problems.
Namely:

The scrolling position of the body will be lost, that is, the scrollTop property value of the body will change to 0.

This new problem is more troublesome than rolling penetration itself, so this scheme is to be optimized.

Option two:

Since adding the module "open" class will cause the rolling position of the body to be lost, why don't we save it before the rolling position is lost, and set the saved rolling position back before exiting the pop-up window. Then start coding in this direction.

// Part css
.modal_open {
  position: fixed;
  height: 100%;
}

// Part js
/**
 * ModalHelper helpers resolve the modal scrolling issue on mobile devices
 * https://github.com/twbs/bootstrap/issues/15852
 */
var ModalHelper = (function(bodyClass) {
    var scrollTop;
    return {
        afterOpen: function() {
            scrollTop = document.scrollingElement.scrollTop  ||
                        document.documentElement.scrollTop || 
                        document.body.scrollTop;
            document.body.classList.add(bodyClass);
            document.body.style.top = -scrollTop + 'px';
        },
        beforeClose: function() {
            document.body.classList.remove(bodyClass);
            document.scrollingElement.scrollTop = document.documentElement.scrollTop = document.body.scrollTop = scrollTop;
        }
    };
})('modal_open');

// method
modalSwitch: function(){
    let self = this;
    if( self.switchFlag === 'close' ){
        ModalHelper.afterOpen();
        self.switchFlag = 'open';
    }else{
        ModalHelper.beforeClose();
        self.switchFlag = 'close';
    }
}

Scheme II can achieve the following effects:

When the pop-up window scrolls, the lower body is fixed and cannot be scrolled;
The rolling position of the body will not be lost;
body has scroll event;

Scheme 2 can meet most of the pop-up window requirements, and the test party is not asking other questions after the test, which is a perfect solution.

Posted by jworisek on Sun, 08 Dec 2019 08:34:20 -0800