跳至主要內容
Element-UI、scrollbar-width.js

获取浏览器滚动条宽度,一般用于弹出层的时候,设置body的右边距,防止overflow: hidden的时候元素抖动。

scrollbar-width.js

import Vue from 'vue';

let scrollBarWidth;

export default function() {
  // 如果是服务器端渲染,则浏览器滚动条的宽度为0
  if (Vue.prototype.$isServer) return 0;
  if (scrollBarWidth !== undefined) return scrollBarWidth;

  const outer = document.createElement('div');
  outer.className = 'el-scrollbar__wrap';
  // 强制出现滚动条
  // .el-scrollbar__wrap {
  //   overflow: scroll;
  //   height: 100%
  // }
  outer.style.visibility = 'hidden';
  outer.style.width = '100px';
  outer.style.position = 'absolute';
  outer.style.top = '-9999px';
  document.body.appendChild(outer);
  // https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/offsetWidth
  const widthNoScroll = outer.offsetWidth;
  outer.style.overflow = 'scroll';

  const inner = document.createElement('div');
  inner.style.width = '100%';
  outer.appendChild(inner);

  const widthWithScroll = inner.offsetWidth;
  outer.parentNode.removeChild(outer);
  // 父元素出现滚动条,子元素无滚动条,父元素减去子元素的宽度就是滚动条宽度
  scrollBarWidth = widthNoScroll - widthWithScroll;

  return scrollBarWidth;
};

fxss原创大约 2 分钟VueElement-UI