js 禁止/允许页面滚动小白知识_滚动使用帮助

方法一:IOS允许滚动会无效function scrControl(t){if(t == 0){ //禁止滚动document.body.addEventListener(‘touchmove’, function (e) {e.preventDefault();}, { passive: false }); //passive 参数不能省略,用来兼容io

js 禁止/允许页面滚动小白知识

方法一: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 }能防止页面卡顿。

js 禁止/允许页面滚动小白知识_滚动使用帮助

可以通过传递 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});
    }
}

方法三:

//禁止页面滑动
stop(){
      var mo=function(e){passive: false ;};
      document.body.style.overflow='hidden';
      document.addEventListener("touchmove",mo,false);//禁止页面滑动
  },
//取消滚动限制
move(){
      var mo=function(e){passive: false };
      document.body.style.overflow='';//出现滚动条
      document.removeEventListener("touchmove",mo,false);
},
海计划公众号
(0)
上一篇 2020/03/24 05:42
下一篇 2020/03/24 05:41

您可能感兴趣的内容