js获取页面滚动条宽度

let cached;
function getScrollBarSize(fresh){
	//fresh 是否重新获取, cached: 是否获取过
	if(fresh || cahced===undefined) {
		const inner = document.createElement('div');
		inner.style.width = '100%';
		inner.style.height = '200px';

		const outer = document.createElement('div');
		outer.style.position = 'absolute';
		outer.style.top =  0;
		outer.style.left = 0;
		outer.style.visibility = 'hidden';
		outer.style.width = '200px';
		outer.style.height = '150px'; //父元素高度比内部元素高度小
		outer.style.overflow = 'hidden';
		outer.appendChild(inner);
	
		document.body.appendChild(outer);
		
		const widthContained = inner.offsetWidth;
		outer.style.overflow = 'scroll'; //让滚动条显示出来
		let widthScroll = inner.offsetWidth; //offsetWidth: content+padding+border
		
		if(widthContained === widthScroll){
			widthScroll = outer.clientWidth; //clientWidth: content + padding
		}
		document.body.removeChild(outer);
		/**
			const widthContained = outer.offsetWidth;
			const widthScroll = outer.clientWidth;
			document.body.removeChild(outer);
		**/

		
		cached = widthContained - widthScroll
	}
	return cached;
}
发布了66 篇原创文章 · 获赞 13 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/haoyanyu_/article/details/95048590