1. Scenario: When we develop mobile terminals, there is a high probability that the page will not be displayed on one screen. At this time, there will be a scrolling effect. At this time, when we click a button and a pop-up window appears, you will find that you are on the pop-up window When scrolling up and down, it will cause the page under the mask to scroll. Although there is no problem in function, the sense is not good.
2. Solve
method 1:
1. Add the overflow:hidden attribute to the html tag (disadvantage: scroll the page first, then pop up a pop-up window, and the page will return to the top)
let body=document.getElementsByTagName('html');
if(modelIsShow){
body.style.overflow='hidden';
}else{
body.style.overflow='';
}
2. Prohibit the default event of touchmove (disadvantage: scrolling event fails)
document.addEventListener('touchmove',function(e){
if(modelIsShow){
e.preventDefault();
}
},{passive: false})
3. Change the body style (measured and feasible)
/**
* 阻止背景滚动
*
* @param Boolean flag [是否阻止背景滚动]
*/
const preventBack = (flag) => {
if (flag) {
const top = document.documentElement.scrollTop || document.body.scrollTop;
document.body.style.cssText += `
position: fixed;
width: 100vw;
left: 0;
top: ${-top}px;
`;
} else {
const top = document.body.style.top;
document.body.style.cssText += `
position: static;
`;
window.scrollTo(0, Math.abs(parseFloat(top)));
}
};