有趣且重要的JS知识合集(14)浏览器获取滚动条宽度

当很多时候,滚动条宽度也会影响到我们页面上的布局,那怎么去计算这宽度呢?浏览器没有提供这方法来计算,那么我们就模拟一个有滚动条的div,然后算出宽度~

小知识:offsetWidth和clientWidth都是只读属性,但是offsetWidth是包括border的,而clientWidth只包含padding,不包含border的,所以可以利用这个差距来计算border宽度

    /**
     * 获取滚动条宽度
     */
    getScrollbarWidth() {
      const scrollDiv = document.createElement('div');
      scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;'
      document.body.appendChild(scrollDiv)
      const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
      document.body.removeChild(scrollDiv)
      return scrollbarWidth
    },

猜你喜欢

转载自blog.csdn.net/qq_39404437/article/details/128091713