在编写javascript代码时,有时需要用到滚动条的宽度,然而不同浏览器下滚动条的宽度可能不同。
在jquery ui源代码中发现这样的一段代码:
var scrollbarWidth=function () {
if (cachedScrollbarWidth !== undefined) {
return cachedScrollbarWidth;
}
var w1, w2,
div = $("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),
innerDiv = div.children()[0];
$("body").append(div);
w1 = innerDiv.offsetWidth;
div.css("overflow", "scroll");
w2 = innerDiv.offsetWidth;
if (w1 === w2) {
w2 = div[0].clientWidth;
}
div.remove();
return (cachedScrollbarWidth = w1 - w2);
}
这样就可以使用javascript来获取当前浏览器的滚动条宽度。
对其实现原理进行简单分析:
1、向页面添加一个div元素,这个div内又有一个div;
2、外部的div设置了宽度(50px)和高度(50px),溢出隐藏;
3、内部div设置的高度(100px)大于外部div的高度,宽度自动;
4、获取此时内部div的宽度w1(offsetWidth);
5、使外部div溢出滚动(出现垂直滚动条);
6、此时内部div宽度由于滚动条而变窄w2(offsetWidth);
7、w1-w2为滚动条宽度;
代码中使用到了jQuery,稍作修改就可以变成一个不需要jQuery的版本:
var scrollbarWidth=function () {
var w1, w2, outer,inner;
outer = document.createElement('div');
inner = document.createElement('div');
outer.appendChild(inner);
outer.style.display = 'block';
outer.style.position = 'absolute';
outer.style.width = '50px';
outer.style.height = '50px';
outer.style.overflow = 'hidden';
inner.style.height = '100px';
inner.style.width = 'auto';
document.body.appendChild(outer);
w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
document.body.removeChild(outer);
return w1 - w2;
}