js开启和禁止页面滑动

在移动端中,由于机型的不同,往往在弹窗的时候会出现页面的穿透事件,使得原页面还是能够进行滑动,这是我们不想看到的效果。
前提
html,body{
height: 100%;
height: 100vh;
}
首先,建立一个函数

function bodyScroll(event){  
    event.preventDefault();  
} 

之后在触发弹窗的时候禁止页面滚动

document.body.addEventListener('touchmove',bodyScroll,false);  
$('body').css({'position':'fixed',"width":"100%"});

关闭弹框时开启页面滚动

document.body.removeEventListener('touchmove',bodyScroll,false);   
$("body").css({"position":""});                                 

注意:切不可以下写法

document.body.addEventListener('touchmove', function (event) {  
    event.preventDefault();  
},false);  
document.body.removeEventListener('touchmove', function (event) {  
    event.preventDefault();  
},false);

方法二:

mounted() {
    this.scrollTop = document.documentElement.scrollTop
      || window.pageYOffset
      || document.body.scrollTop;
    document.body.style.position = 'fixed';
    document.body.style.top = `${-this.scrollTop}px`;
  },
  beforeDestroy() {
    document.body.style.position = '';
    document.body.style.top = '';
    window.scrollTo(0, this.scrollTop); // 回到原先的top
  },

你可能感兴趣的:(js开启和禁止页面滑动)