【踩坑】如何解决移动端弹窗滑动带着整个网页滑动

174 阅读1分钟

打开弹窗时,在移动端如何阻止在弹窗范围内滑动时,整个页面也跟着滑动?尝试过弹窗打开时给根节点添加overflow:hidden;touch-action: none;,但移动端不适用,既然要阻止页面滚动,可以尝试下固定视窗

具体思路:弹窗和蒙层打开时给body加上position: fixed;,这里需要注意top的值,因为将页面固定后内容会回到最顶端,所以需要记录下top的值

const preventScrollHtml = (fixed: boolean) => {
    let bodyEl = document.body;
    let top = 0;
    // 需要吸顶的元素与顶部的距离
    const headNodeHeight = document.getElementById('head')?.offsetHeight || 78;
    if(fixed) {
      top = window.scrollY;
      setPreviousScrollY(window.scrollY);
      if(top < headNodeHeight) {
        top = headNodeHeight
      }
      bodyEl.style.setProperty('position', 'fixed', 'important');
      bodyEl.style.top = `-${top}px`;
      document.documentElement.style.setProperty('height', '100vh', 'important');
    }else {
      bodyEl.style.position = '';
      bodyEl.style.top = '';
      document.documentElement.style.setProperty('height', 'auto', 'important');
      window.scrollTo(0, previousScrollY); //回到原来的top
    }
  }