美文网首页让前端飞
取滚动条宽度

取滚动条宽度

作者: 歇歇 | 来源:发表于2019-01-07 17:12 被阅读2次

原理

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

相关文章

网友评论

    本文标题:取滚动条宽度

    本文链接:https://www.haomeiwen.com/subject/ejtprqtx.html