isServer
const isServer = Vue.prototype.$isServer;
原创大约 3 分钟
const isServer = Vue.prototype.$isServer;
获取浏览器滚动条宽度,一般用于弹出层的时候,设置body
的右边距,防止overflow: hidden
的时候元素抖动。
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;
};