preface

Recently in the process of writing plug-ins , Need to use JS
Determine if there is a scroll bar , Have a search , The general methods are almost the same , But it's all a little verbose , The code is not concise enough . Finally, by referring to different methods , Write a relatively simple method . It is necessary to calculate the width of the scroll bar while judging the scroll bar , Share with you through this article .

Why to judge scroll bar



Judging the demand of scroll bar is often used in pop-up plug-ins , Because pop ups are mostly added overflow: hidden Properties of , If the page is long , After adding this property, the page will shake .

To enhance the user experience , Add by judging whether there is a scroll bar margin-left Property to offset overflow: hidden Scroll bar position after .

How to judge whether there is a scroll bar

It's just a line JS Can , Test compatibility IE7
function hasScrollbar() { return document.body.scrollHeight >
(window.innerHeight || document.documentElement.clientHeight); }
Normally , use document.body.scrollHeight > window.innerHeight You can judge .

But in IE7,IE8 in window.innerHeight by underfined, So for compatibility IE7,IE8, Need to use
document.documentElement.clientHeight Property calculate window height .

How to calculate the width of scroll bar

Take pop ups for example , because IE 10 The above and the scroll bar of mobile browser are transparent styles that do not occupy the page width ( among IE 10 The above browsers can be accessed through CSS
Property to restore the original scroll bar style ), So in order to further enhance the user experience , We also need to calculate the width of the scroll bar , Add reasonable margin-left numerical value .



The method of calculating the width of scroll bar is simple , Create a new one with scroll bar div element , Through the offsetWidth and clientWidth
The difference of , I will learn from it here Magnific-popup Method in
function getScrollbarWidth() { var scrollDiv = document.createElement("div");
scrollDiv.style.cssText= 'width: 99px; height: 99px; overflow: scroll;
position: absolute; top: -9999px;'; document.body.appendChild(scrollDiv); var
scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);return scrollbarWidth; }
summary

use JS
It may not be difficult to implement a function , But as a programmer, we should always think about how to implement this function more simply and elegantly , And always based on the principle of improving user experience . For condition judgment , Maybe the logical judgment of ten lines may only need one line , I've been feeling a lot lately , And be good at using ternary expression instead
if..else To simplify the code .