取滚动条宽度

原理

  • clientWidth表示元素的内部宽度,包括内边距,不包括边框和外边距、滚动条
  • offsetWidth表示元素的布局宽度,包括内边距、边框、滚动条,不包括外边距

所以在元素没有边框时,等式offsetWidth - clientWidth = scrollWidth成立

实现

/**
 * @description 获取滚动条宽度
 */
function getScrollWidth() {
  let node = document.createElement('div')
  node.style = 'overflow: scroll; visibility: hidden;'
  document.body.append(node)
  let w = node.offsetWidth - node.clientWidth
  node.remove()
  return w
}

你可能感兴趣的:(取滚动条宽度)