elementUI——scrollbar-width获取滚动条宽度

说明:以下基于elementUI@2.13.1。
element-ui\src\utils\scrollbar-width.js中:

import Vue from 'vue';

let scrollBarWidth;

export default function() {
  if (Vue.prototype.$isServer) return 0;
  if (scrollBarWidth !== undefined) return scrollBarWidth;

  const outer = document.createElement('div');
  outer.className = 'el-scrollbar__wrap';
  outer.style.visibility = 'hidden';
  outer.style.width = '100px';
  outer.style.position = 'absolute';
  outer.style.top = '-9999px';
  document.body.appendChild(outer);

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

第一步,创建一个100px宽度的div元素插入body中,并设置滚动模式,widthNoScroll保存该div的offseWidth,即100;
第二步,创建一个100%宽度的div元素,插入到第一步创建的div中,widthWithScroll保存offseWidth值,在本人电脑中为83;
第三步,返回值为widthNoScroll - widthWithScroll,即17。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。