Javascript 如何暂时锁定网页的滚动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6411282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to lock scrolling of a web page temporarily?
提问by Rajat Gupta
How can I lock scrolling of a webpage temporarily when a dialog box is displayed ? I have a dialog box within which I want to enable scrolling after deactivating scrolling from the overlayed webpage.
如何在显示对话框时暂时锁定网页的滚动?我有一个对话框,我想在其中从覆盖的网页停用滚动后启用滚动。
Is there a js command to temporarilydisable scrolling ?
是否有 js 命令可以暂时禁用滚动?
采纳答案by Kamiel Wanrooij
You could set a container element or maybe even the body to overflow: hidden
with a width and height of the browser window. This way any overflowing content will fall off the page and scroll bars are never displayed. This can be set in a css statement like body.dialog-open { overflow: hidden; }
. You can then add and remove the .dialog-open
classname when the dialog opens and closes.
您可以将容器元素或什至主体设置为overflow: hidden
具有浏览器窗口的宽度和高度。这样,任何溢出的内容都会从页面上脱落,并且永远不会显示滚动条。这可以在像 .css 这样的 css 语句中设置body.dialog-open { overflow: hidden; }
。然后,您可以.dialog-open
在对话框打开和关闭时添加和删除类名。
The width and height might not be required if setting this on the body, but I'd have to check browser compatibility on that one. Might get some unexpected results there.
如果在主体上设置它,则可能不需要宽度和高度,但我必须检查浏览器的兼容性。可能会在那里得到一些意想不到的结果。
edit:
If you want scrolling inside your dialog you can set overflow: auto
there, with a height set on that element.
编辑:如果您想在对话框内滚动,您可以在overflow: auto
那里设置,并在该元素上设置高度。
Older browsers (most notably IE) might show a horizontal scrollbar as well, you might have to set overflow-x: hidden
if that is the case.
较旧的浏览器(尤其是 IE)也可能会显示水平滚动条,overflow-x: hidden
如果是这种情况,您可能需要进行设置。
Also see: CSS div element - how to show horizontal scroll bars only?for more information on scrollbars.
另请参阅:CSS div 元素 - 如何仅显示水平滚动条?有关滚动条的更多信息。
回答by Limpan
EDITTry this:
编辑试试这个:
On dialog open (remove scrollbar and prevent user from scrolling):
在对话框打开时(删除滚动条并防止用户滚动):
$('body').css({'overflow':'hidden'});
$(document).bind('scroll',function () {
window.scrollTo(0,0);
});
On Dialog Close(allow user to scroll again):
在对话框关闭时(允许用户再次滚动):
$(document).unbind('scroll');
$('body').css({'overflow':'visible'});