vw计算屏幕宽度的时候受Y轴滚动条的影响

20 阅读1分钟

今天做了一个固定吸顶的操作,元素吸顶之后要求宽度100%背景为白色,此时定位了,100%没办法找到父级宽度为基准。此时我就用vw,发现vw计算宽度把Y轴的滚动条也算进去了,导致出现横向滚动条。

  • 思路就是算出Y轴滚动条的宽度,然后减去
// start------------解决tabs栏定位吸顶的时候用vw单位取100%宽度受到Y轴滚动条的影响
  const [isHaveScrollbar, setIsHaveScrollbar] = useState(false);
  const [scrollbarWidth, setScrollbarWidth] = useState(15);
  const hasScrollbar = () => {
    console.log(
      document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight)
    );
    return (
      document.body.scrollHeight > (window.innerHeight || document.documentElement.clientHeight)
    );
  };
  const getScrollbarWidth = () => {
    const container = document.createElement('div');
    container.style = 'border: 1px solid red; height: 130px';
    document.body.appendChild(container);
    container.style.overflow = 'scroll';
    const inner = document.createElement('div');
    inner.style = 'border: 1px solid blue; height: 2330px';
    container.appendChild(inner);
    const width = container.offsetWidth - inner.offsetWidth;
    document.body.removeChild(container);
    return width;
  };
  useEffect(() => {
    // setTimeout(() 
    setIsHaveScrollbar(hasScrollbar());
    setScrollbarWidth(getScrollbarWidth());
    // }, 500);
  }, []);
  // end------------解决tabs栏定位吸顶的时候用vw单位取100%宽度受到Y轴滚动条的影响