jQuery/CSS: fixed overlay should not allow scrolling of background?
i have a overlay box that is fixed and centered on the screen. The page itself is rather long and has a vertical scrollbar.
I'd like to disable scrolling of the page itself once the overlay is shown. However I can't disable scroll completely because some overlays do have overflow-y:scroll
for themselves. So the content in the overlay should be scrolled but the page开发者_如何学运维 itself should be stuck.
Any idea how to solve that with jquery or css?
The quickest and dirtiest way I can think of is to attach an event listener to the window for scroll events, and preventDefault() if your overlay is visible.
like so (using jquery).
window.addEventListener('scroll', function(e){
var el = $('.overlay.active');
if( el.length > 0 ){
e.preventDefault();
}
});
Hope this is what your looking for.
You can set the body
to overflow: hidden
. This will prevent scrolling. Child's overflow declarations stay unaffected. I have done a little fiddle.
Just an adjustment to Marc's jQuery solution. My code disables the body scroll as the overlay appears, then when the body or overlay close button is clicked, the body scroll is re-enabled.
/*We disable the scroll*/
$(function() {
/*This is where we specify what button is being clicked to open the
overlay, change at will.*/
$('#overlay1').click(function() {
/*This is where we specify what part of the page is gonna disable the
scroll, in this case the body.*/
$('body')
.css('overflow', 'hidden');
});
/*Now we re-enable the scroll*/
/*This is where we specify the the part of the overlay that is being
clicked to close it, in this case, the body and the .close, change at will.*/
$('body, .close').click(function() {
/*This is where we specify the part of the page we are re-enabling
the scroll, in this case the body.*/
$('body')
.css('overflow', 'visible');
});
});
Here's a little JSFiddle of my script in action.
You can position your overlay as a {position: fixed;}
. That will keep your overlay in your screen even if your page scrolls.
You could create an full width and full height container, with position: fixed
. And inside this container create your actual overlay with info. The container basically blinds the user from scrolling or interacting with the page.
精彩评论