问题
Using responsive Layout and a lot of CSS to create a Webpage, I am having a problem with scrollbars being hidden or shown and changing the layout by 17px.
The main problem is that on OSX the scrollbars hover over the entire Layout without affecting it, but in any browser on Windows for example the scrollbar is part of the layout and therefore moving it to the left by its width of 17px.
Trying to solve this I started to detect browsers like:
if($.browser.chrome) {
// adapt layout by 17px
} else if ($.browser.mozilla) {
// adapt layout by 17px
} else if ($.browser.safari) {
// dont adapt layout by 17px
}
But after reading a lot of posts on that topic, I realized that instead of detect the browser many people recommend feature detection. So is there a way to find out how the browser is handling the scrollbars? Whether they will be part of the pagelayout or they will just hover on top of everything like in safari?
Thanks for your help!
回答1:
This is easy to measure. On a scrollable element, the scrollbar thickness is simply:
var scrollbarWidth = scrollableEl.offsetWidth - scrollableEl.clientWidth;`
As explained very well by David Walsh. The scrollbar width/height is zero on:
OSX (unless the Mouse settings have been modified, or before Lion).
touch device browsers (Android, iOS, Windows Phone).
IE12 Edge in Tablet Mode (dynamically changeable, scrollbars show and hide and page redraws when Tablet mode is changed. I think the change is detectable by registering for the resize event and testing the scrollbar width).
Can be changed by CSS e.g.
::-webkit-scrollbar { width: 1em; }
e.g.-ms-overflow-style: none
(documentation).May be zero if element is not in document yet (also maybe if script running in
<head>
?).
Other notes:
Modernizr has a hiddenscrollbar feature detection which detects if zero width scrollbars used.
Height difference should also measure this, but it wasn't reliable in IE8 (especially unreliable after resize event due to zoom change), so I have always used width difference.
If the width is non-zero, it can also change due to: (1) page zoom changes (width stays same as physical pixels on some browsers, therefore logical pixels changes. Although pinch-zoom acts differently), (2) Style changes like
-webkit-scrollbar
, (3) Desktop theme changes (widths different for major themes, or personalized themes).
Here are some links to testers:
Some simple plain JavaScript code (probably better to make the div permanent to avoid reflow calcs).
Modernizr cow test which AFAIK gives hiddenscrollbar as true if scrollbarwidth is zero (also see cssscrollbar).
Some ugly jQuery code
回答2:
The hiddenscroll test should be what you are looking for in Modernizr. Its not in the main library yet, but you can build a custom version of the v3 beta (which includes this test) at v3.modernizr.com
来源:https://stackoverflow.com/questions/23494468/detect-different-kind-of-scrollbars-eg-normal-hidden-osx