javascript HTML 将滚动条附加到模态内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10238851/
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
HTML Attach Scrollbar to Modal Content
提问by Harper
I am creating a page similar to Pinterest where items flow vertically as the user scrolls. When the user clicks on one of these items, a modal with related content opens. Currently, the modal is an absolutely-positioned div.
我正在创建一个类似于 Pinterest 的页面,其中项目在用户滚动时垂直流动。当用户单击这些项目之一时,会打开一个带有相关内容的模式。目前,模态是一个绝对定位的 div。
Both the modal and the background (item list) are longer than the user's browser height. How can I make the scroll bar on the browser represent the modal div's height and not the background's height, and then set it back when the modal is closed?
模态和背景(项目列表)都比用户的浏览器高度长。如何让浏览器上的滚动条代表模态 div 的高度而不是背景的高度,然后在模态关闭时将其重新设置?
I tried hiding the background and showing the modal, but then when I hide the modal and show the background it scrolls the page all the way back up again. I'd like to keep the background slightly visible, like on Pinterest's main page.
我尝试隐藏背景并显示模态,但是当我隐藏模态并显示背景时,它会再次滚动页面。我想让背景稍微可见,就像在 Pinterest 的主页上一样。
回答by CaptainBli
I would do something like this for the modal div:
我会为模态 div 做这样的事情:
<div style="background-color: rgba(255,255,255, 0.93);position:fixed;
overflow-x:auto;overflow-y:scroll;bottom:0;left:0;right:0;top:0;
z-index:9999;"></div>
It creates a div that fills the whole document and then adds the scrollbar for the middle content. As soon as you show the modal you need to set the main body (the background) of your page to:
它创建一个填充整个文档的 div,然后为中间内容添加滚动条。显示模态后,您需要将页面的主体(背景)设置为:
style="overflow:hidden"
You could use jquery like:
您可以使用 jquery,如:
$("body").css("overflow", "hidden");
It is important to get the main body to set the overflow to hidden in order to remove the other scroll bar. When I tested this in Firefox, it worked. I had a div as described and then set the body style and it worked. I was also in the middle of the document when I tested it. The background document stayed where it was and didn't move.
重要的是让主体将溢出设置为隐藏以删除另一个滚动条。当我在 Firefox 中测试时,它起作用了。我有一个如上所述的 div,然后设置了 body 样式并且它起作用了。当我测试它时,我也在文档的中间。背景文件留在原地不动。
回答by aziz punjani
Give the modal div a fixed height and a css property of overflow:scroll
给模态 div 一个固定的高度和一个 css 属性 overflow:scroll