I am trying to detect if there is a vertical scrollbar or not on the browser window (if the content exceeds the window height and overflows). I have tried document.body.scrollTop
, window.pageYOffset
, and document.body.style.height
... none of these are working!
Upon doing a window.alert
test on variables initialized with these properties, pageYOffset
always returns 0 no matter if there is a scrollbar or not, and the other two return what seems to be an empty String.
My only idea is that maybe CSS positioning conflicts are causing this, but there seem to be no such conflicts... Any ideas, solutions, workarounds?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
This
window.innerWidth - document.documentElement.clientWidth
returns the width of the vertical scroll-bar of the browser-window, and 0
if there is no scroll-bar.
So, you could have a function...
function windowHasVerticalScrollbar () {
return window.innerWidth - document.documentElement.clientWidth > 0;
}
Unfortunately, IE8 and IE7 don't support the window.innerWidth
value, so this technique will not work in those browsers. (However, it does work in IE9 and all the other browsers).
Also, since the documentElement
is the <html>
element (the root element of the web-page), if you set styles on that element (like margins, absolute positioning, etc.), the calculation may return incorrect results.