获取滚动条的宽度

2,971 阅读1分钟

为什么需要获取滚动条的宽度

最近在写全屏弹窗组件的时候,当弹窗出现时会给body设置overflow:hidden,但是当页面的高度大于一屏时会出现抖动的现象,经分析是滚动条的原因;为了增强用户体验,通过判断是否有滚动条而添加margin-left属性以抵消overflow: hidden之后的滚动条位置,所以就需要计算滚动条的宽度了。

原理

  1. 创建两个div嵌套在一起
  2. 外层的div设置固定宽度和overflow:scroll
  3. 滚动条的宽度=外层div的offsetWidth-内层div的offsetWidth

与案例题

实现代码

/**
 * 获取滚动条的宽度
 */
getScrollWidth() {
    const scroll = document.createElement("div");
    const scrollIn = document.createElement("div");
    scroll.appendChild(scrollIn);
    scroll.style.width = "100px";
    scroll.style.height = "50px";
    scroll.style.overflow = "scroll";
    scroll.style.marginLeft = "-100000px";
    document.body.appendChild(scroll);
    const scrollInWidth = scrollIn.offsetWidth;
    const scrollWidth = scroll.offsetWidth;
    const tmp = setTimeout(() => {
        document.body.removeChild(scroll);
        clearTimeout(tmp);
    }, 10);
    return scrollWidth - scrollInWidth;
}