說明
用來獲取滾動條寬度。
源碼解析
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'; // 同樣會加入overflow: scroll
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%'; // 寬度為100%,實際上因為父級有滾動條,父級的 width 會變成 100px - 滾動條寬度
outer.appendChild(inner); // 插入
const widthWithScroll = inner.offsetWidth; // 內部寬度
outer.parentNode.removeChild(outer); // 移除
return widthNoScroll - widthWithScroll; // 滾動條寬度
};