Disabling Scrollbars without Hiding Them
In web development, it is occasionally necessary to disable scrollbars on a parent element while using a lightbox. However, merely hiding the scrollbars using overflow: hidden is often undesirable, as it can cause the site to jump and occupy the space where the scrollbar was.
There is a viable solution that allows for disabling scrollbars while still displaying them. If the page under the lightbox can be positioned at the top, you can utilize the following CSS code:
body { position: fixed; overflow-y: scroll; }
This will display the scrollbar but prevent the content from being scrolled. To restore the scrollbars after closing the lightbox, simply revert these properties:
body { position: static; overflow-y: auto; }
This approach requires no modification of scroll events.
Addressing Pre-existing Scroll Positions
If the page is already scrolled before the lightbox is opened, you can retrieve the current scroll position through JavaScript and assign it as the top property of the body element. This will maintain the current scroll position during lightbox usage.
CSS
.noscroll { position: fixed; top: var(--st, 0); inline-size: 100%; overflow-y:scroll; }
JavaScript
const b = document.body; b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px"); b.classList.add('noscroll');
By implementing this solution, you can effectively disable scrollbars without hiding them, preserving the intended visual presentation of your webpage.
The above is the detailed content of How Can I Disable Scrollbars Without Hiding Them in Web Development?. For more information, please follow other related articles on the PHP Chinese website!