1.給html標(biāo)簽添加overflow:hidden屬性(弊端:先滾動(dòng)頁面援雇,后彈出彈窗,頁面會(huì)回到頂部)
let ele=document.getElementsByTagName('html');
if(modelIsShow){
ele.style.overflow='hidden';
}else{
ele.style.overflow='';
}
2.禁止touchmove的默認(rèn)事件(弊端:滾動(dòng)事件失效)
document.addEventListener('touchmove',function(e){
if(modelIsShow){
e.preventDefault();
}
},{passive: false})
3.改變body樣式(實(shí)測可行)
/**
* 阻止背景滾動(dòng)
*
* @param Boolean flag [是否阻止背景滾動(dòng)]
*/
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)));
}
};