使用 jquery 将覆盖层放置在页面的中心
这应该是一个简单的问题,但我似乎无法弄清楚。我使用 jquery 制作了一个弹出窗口,我希望它位于页面的中心。无论网站如何调整、分辨率如何。现在我只是用 CSS 绝对定位它,但问题是,如果你移动页面,它不会移动覆盖层,这取决于页面上有多少内容。有没有办法用 jquery 定位它,使其也位于窗口的中心?
谢谢!
This should be a simple question, but I can't seem to figure it out. I made a popup using jquery, and I want it positioned in the center of the page. No matter how the site is adjusted and the resolution. Right now I'm just positioning it absolutely with CSS but the problem with that is that if you move the page around it doesn't move the overlay and it depends on how much content is on the page. Is there a way to position it with jquery so it will also be in the center of the window?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为此,您不需要 jQuery。如果目的是始终让 div 位于窗口中央,那么您可以使用 CSS 来实现。
查看工作示例http://jsfiddle.net/5Q6FU/
You do not need jQuery for this. If the purpose is to always have the div in the center of the window, then you can do it with CSS.
Check working example at http://jsfiddle.net/5Q6FU/
你可以得到这样的窗口尺寸:
然后你可以得到你的弹出窗口的尺寸:
做一些计算:
最后定位你的弹出窗口:
我还没有测试过这个,但你应该得到使用的想法。
//编辑
顺便说一句,它可能会像 css 定位一样工作。如果您希望它在页面移动时重新定位,您只需将代码放入函数中,并在页面移动时在事件上调用它即可。
you can get window dimensions like this:
then you can get your popup's dimensions:
do some calculation:
and finaly position your popup:
I haven't tested this but you should get the idea to work with.
//edit
btw it would probably work just as css positioning. If you want it to reposition as the page moves you just put the code to function and call it on events when page moves.
这可以通过 CSS 来完成。如果弹出框是绝对定位的,则将 left 设置为 50%,将 margin-left 设置为负值,无论框宽度的一半是多少。
This can be done with CSS. If the popup box is absolute positioned then set left to 50% and margin-left to negative whatever half the width of the box is.
有几种方法可以实现这一点,即使用户调整窗口大小,保持覆盖层位于中心的一个好方法是执行以下操作:
然后使用 css (您可以选择固定位置并摆脱滚动顶部JavaScript):
There are a few ways to accomplish this, a good one to keep the overlay in the center even if the user resizes the window is by doing the following:
and then have css (you could optionally have position fixed and get rid of the scrollTop in the javascript):