element-ui有这么一个文件,在此做一个记录
这个文件主要是用来计算当前打开组件的浏览器的滚动条宽度的,这样就可以原本的滚动条隐藏,然后自定义一个更好看的滚动条!!!
import Vue from 'vue';
let scrollBarWidth;
export default function() {
// 服务端
if (Vue.prototype.$isServer) return 0;
// 防止重复计算
if (scrollBarWidth !== undefined) return scrollBarWidth;
// 首先创建一个div,隐藏起来,放到视口以外
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);
// 放入浏览器中后获取dom所占宽度
const widthNoScroll = outer.offsetWidth;
// 手动设置成滚动状态
outer.style.overflow = 'scroll';
// 创建一个内部的子dom
const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
// 放入到dom中后获取dom所占宽度
const widthWithScroll = inner.offsetWidth;
// 移除dom
outer.parentNode.removeChild(outer);
// 计算子和父dom宽度的差值,则是滚动条宽度
scrollBarWidth = widthNoScroll - widthWithScroll;
// 把计算好的滚动条返回
return scrollBarWidth;
};