Preventing Scrollbar Scrolling Without Hiding
A common challenge when implementing lightboxes is the need to temporarily disable the scrollbar on the parent page without resorting to overflow: hidden;. This solution can cause undesired jumps and space occupation.
Thankfully, there is a viable approach to disable scrollbars while still displaying them. By utilizing a fixed positioning for elements beneath the overlay, it's possible to achieve this effect. When the overlay is activated, apply the following styles to the body:
body { position: fixed; overflow-y: scroll; }
This will display the scrollbar but disable its functionality. To revert this change upon closing the overlay, simply restore the original styles:
body { position: static; overflow-y: auto; }
In cases where the page has already been scrolled, capturing the current scroll position via JavaScript and setting it as the top property of the body element ensures the page remains in its current scroll position when the overlay is activated. This can be achieved with the following CSS and JS:
.noscroll { position: fixed; top: var(--st, 0); inline-size: 100%; overflow-y: scroll; }
const b = document.body; b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px"); b.classList.add('noscroll');
By implementing this approach, you can effectively disable scrollbars without hiding them, maintaining the desired functionality for both the lightbox and the parent page.
The above is the detailed content of How Can I Prevent Scrollbar Scrolling Without Hiding the Scrollbar?. For more information, please follow other related articles on the PHP Chinese website!