Vue 移动端出现弹出层时,禁止底部页面跟随滑动

1,539 阅读1分钟

背景

最近不在状态 ,感觉自己浑浑噩噩的

需求就是弹出框弹出的时候禁止页面滑动,很多时候用css 就能结局 但是有的时候没办法! 所以想到了用js来解决这个问题!

解决方案 如下:

1.在有弹出框的页面中,加上以下方法,弹出框出现时调用禁止滚动方法stopScroll(),弹出框去掉是调取允许滚动方法canScroll()即可,代码如下:


methods : {
   //禁止滚动
   stopScroll(){
        var mo=function(e){e.preventDefault();};
        document.body.style.overflow='hidden';
        document.addEventListener("touchmove",mo,false);//禁止页面滑动
    },
    //取消滑动限制
    canScroll(){
        var mo=function(e){e.preventDefault();};
        document.body.style.overflow='';//出现滚动条
        document.removeEventListener("touchmove",mo,false);
    }

2.在全局js即main.js中,设置全局函数,在使用到的页面分别调用即可,代码如下:


//弹出框禁止滑动
Vue.prototype.stopScroll = function () {
  var mo = function (e) { e.preventDefault() }
  document.body.style.overflow = 'hidden'
  document.addEventListener('touchmove', mo, false)// 禁止页面滑动
}
 
//弹出框可以滑动
Vue.prototype.canScroll = function () {
  var mo = function (e) {
    e.preventDefault()
  }
  document.body.style.overflow = ''// 出现滚动条
  document.removeEventListener('touchmove', mo, false)
  }

//在需要用的地方页面
//当需要禁止弹出框底部内容滑动时调用:
 
  this.stopScroll ()

  //当需要页面恢复滑动功能时调用:

  this.canScroll ()

有没有人跟我一样? 想组团了。 这根游戏一样:这是团队的游戏,不是个人赛的秀场!!