js 禁止/允许页面滚动

参考:https://blog.csdn.net/huangfu_chunfeng/article/details/46429997
         https://www.cnblogs.com/wxcbg/p/10452985.html
         https://blog.csdn.net/weixin_40126227/article/details/80858990
         https://blog.csdn.net/lyy_666/article/details/82185248

方法一:IOS允许滚动会无效

function scrControl(t){
    if(t == 0){ //禁止滚动
        document.body.addEventListener('touchmove', function (e) {
              e.preventDefault();
        }, { passive: false });  //passive 参数不能省略,用来兼容ios和android
        }else if( t == 1){ //允许滚动
        document.body.addEventListener('touchmove', function (e) {
                  e.returnValue = true;
            }, {passive: false});
    }
}

passive,设置该属性的目的主要是为了在阻止事件默认行为导致的卡顿。等待监听器的执行是耗时的,有些甚至耗时很明显,这样就会导致页面卡顿。即便监听器是个空函数,也会产生一定的卡顿,毕竟空函数的执行也会耗时。加上{ passive: false }能防止页面卡顿。

可以通过传递 passive 为 true 来明确告诉浏览器,事件处理程序不会调用 preventDefault 来阻止默认滑动行为。
如果设置了passive为true,同时又阻止默认行为,阻止是不生效的。

document.addEventListener("touchmove", function(event) {
    event.preventDefault() //不产生作用
}, {passive: true});

方法二:兼容IOS

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

function scrControl(t){
    if(t == 0){ //禁止滚动
        document.body.addEventListener('touchmove', this.bodyScroll, { passive: false });
    }else if( t == 1){ //开启滚动
        document.body.removeEventListener('touchmove',this.bodyScroll, {passive: false});
    }
}
原文地址:https://www.cnblogs.com/linjiangxian/p/11460930.html