【www.bbyears.com--浏览器】
在计算滚动条之前,说明下滚动条的占位方式。在PC浏览器中,滚动条是占位元素的内边距和内容区域的;而在移动浏览器中,滚动条是不占用内边距和内容区域,并且还及时显隐。因此,只需要在在PC浏览器中计算滚动条的宽度,尤其是在全屏弹窗不可滚动的情况中。
详细方法如下(offsetWidth-clientWidth):
function getScrollbarWidth() {
var oP = document.createElement("p"),
styles = {
width: "100px",
height: "100px",
overflowY: "scroll"
}, i, scrollbarWidth;
for (i in styles) oP.style[i] = styles[i];
document.body.appendChild(oP);
scrollbarWidth = oP.offsetWidth - oP.clientWidth;
oP.remove();
return scrollbarWidth;
}
关于offsetWidth和clientWidth更多知识参考JS学习13:screen/client/offset/scroll/inner/avail的width/left。
方法2(clientWidth-clientWidth):
function getScrollbarWidth() {
var oP = document.createElement("p"),
styles = {
width: "100px",
height: "100px"
}, i, clientWidth1, clientWidth2, scrollbarWidth;
for (i in styles) oP.style[i] = styles[i];
document.body.appendChild(oP);
clientWidth1 = oP.clientWidth;
oP.style.overflowY = "scroll";
clientWidth2 = oP.clientWidth;
scrollbarWidth = clientWidth1 - clientWidth2;
oP.remove();
return scrollbarWidth;
}