h5 端页面在弹窗时禁止底部页面滚动

h5 端页面在弹窗时禁止底部页面滚动

方法一: @touchmove.stop.prevent

在遮罩层中添加 @touchmove.stop.prevent ,代码如下:

<div class="dialog-mask" v-if="isDlgShow" @click="closeHandle(2)" @touchmove.stop.prevent /> 

 

方法二:prevent touchmove

通过prevent touchmove 阻止触摸滑动事件touchmove的默认行为,代码如下:

// 弹窗的事件
openHandle () {
      // 在弹窗打开时直接阻止目标元素的滑动事件的默认行为
      document.body.addEventListener('touchmove', this.scrollSetup, { passive: false })
      // 打开弹窗
      this.hideOrShowDlg()     
},
closeHandle (type) {
      document.body.removeEventListener('touchmove', this.scrollSetup)
      // 关闭弹窗
      this.hideOrShowDlg()
},
scrollSetup (e) {
      e.preventDefault()
      e.stopPropagation()
},
hideOrShowDlg(){
      this.showDlg = !this.showDlg
}

 

方法三:position:fixed

通过 position:fixed,在弹窗打开时,将目标元素进行固定,在关闭时恢复。

由于定位会改变元素在页面上的位置,所以需要在fixed前记录元素的位置,取消fixed之后将元素又滚动到原来的位置。

代码如下所示:

<script>
export default {
  name: "",
  data () {
    return {
      showDlg: false
    }
  },
  watch: {
  },
  created () {
  },
  mounted () {   
  },
  methods: { 
    openHandle () {
      /** ------------------ 跳出弹窗页面禁止滚动设置开始 ------------------ */    
      this.preventScoll(true)
      /** ------------------ 跳出弹窗页面禁止滚动设置结束 ------------------ */

      // 打开弹窗
      this.hideOrShowDlg()      
    },
    closeHandle () {
      /** ------------------ 关闭弹窗时移除禁止页面滚动设置开始 ------------------ */ 
      this.preventScoll(false)
      /** ------------------ 关闭弹窗时移除禁止页面滚动设置结束 ------------------ */

      // 关闭弹窗
      this.hideOrShowDlg()
    },
    hideOrShowDlg(){
      this.showDlg = !this.showDlg
    },
    /**
      * 阻止背景滚动
      * @param  Boolean  flag    [是否阻止背景滚动]
    */ 
    preventScoll (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)))
      }
    }
  }
}
</script>
posted @ 2022-11-17 09:33  入世凡尘  阅读(1156)  评论(0)    收藏  举报