1. Introduction

When we implement the page shell layer, there is usually a black translucent full-screen mask behind the shell layer, and we usually set position:fixed to this mask element. When the scroll bar appears on the page and the mask appears, if we scroll the mouse, we will find that the page behind the mask can be rolled, which may divert the user’s attention from the pop-up layer to the page behind it, which gives the user a bad feeling. We can solve this problem by adding overflow: Hidden to the root element. In practice, this leads to another problem, as shown in the GIF below.

2. Problem description



If you are careful, you can find that the main body of the web page shifts to the right when the mask appears when you click the button. When the mask disappears, the main body of the web page shifts back to the original place.

3. Cause of the problem

We know that the browser scroll bar takes up a certain width, and when you add overflow: Hidden to the root element, the disappearance of the scroll bar will cause the page width to change, causing the page to wobble.

4. How to solve it

Now that we know that the page wobbles because the scrollbar disappears, when masked, we can solve the problem by filling the root element with a transparent right border property with the same width as the scrollbar disappears.

var widthBar = 17; Var root = document.documentElement; var button = document.querySelector('.js-btn'); var modal = document.querySelector('.js-modal'); //show modal button.onclick = function() { if (typeof window.innerWidth == 'number') { widthBar = window.innerWidth - root.clientWidth; } root.style.overflow = 'hidden'; root.style.borderRight = widthBar +'px solid transparent'; modal.style.display = 'block'; } //hide modal modal.onclick = function() { root.style.overflow = ''; root.style.borderRight = ''; modal.style.display = 'none'; }Copy the code

As a special note, the width of the scroll bar varies from browser to browser. It is 17px for Chrome, Firefox, Baidu, 360 and Safari, 21px for IE7 / IE8, 17px for IE9 + and 17px for Edge and 16px for Edge.


Preview after modification:



5, summary

If you have any questions or better suggestions, feel free to leave them in the comments section. Writing is limited, if the article is not correct, hope to inform!