弹出弹框时如何禁止页面底部滑动

283 阅读1分钟
  1. 方式一,利用addEventListener的第三个参数,在scroll事件的捕获阶段,body上加e.preventDefault()方法,禁止事件向下流动
componentDidUpdate() {
    // 弹框弹出时禁止滚动
    const { showModal } = this.state
    if (showModal) {
      //capture:布尔值,表示该事件是否在捕获阶段触发监听函数。
      //passive:布尔值,表示监听函数不会调用事件的preventDefault方法。如果监听函数调用了,浏览器将忽略这个要求,并在监控台输出一行警告。
      document.body.addEventListener('touchmove', this.stopTouch, { passive: false, capture: true })
    } else {
      document.body.removeEventListener('touchmove', this.stopTouch, { capture: true })
    }
  }
  stopTouch = (e: any) => {
    e.preventDefault();
  }

但是这种方法也存在一定的局限性,比如modal上的内容也需要滚动,就出现问题了,这时候就需要下边这种了
2. 方式二,当弹框出现时,在body上加样式

<body style="width: 100%;height: 100%;overflow: hidden"></body>

这种方式的局限性:当页面已经滚动了一定距离,再弹出弹框时,页面会回到顶部,体验上会有一定的问题

总结:以上两种方式大家根据真实的情景需灵活运用