计算滚动条的宽度--js


原理

  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;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM