浏览器的异同没有统一的方法获取纵向或者横向滚动条的实际宽度
动态创建dom结构根据当前浏览器计算 纯在滚动条和不存在滚动条之间的 offsetWidth 差值
const outer = document.createElement('div');
outer.className = '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);
return widthNoScroll - widthWithScroll;
网友评论