如何使用jQuery将div放在页面中间并在窗口重新resize时保持居中?

有没有人知道任何jQuery脚本将div保持在中间位置,当窗口重新resize时,它还会保持居中? 我正在构建一个灯箱插件,我需要它留在中间。 我尝试使用CSS,但它不起作用。

另外我需要它在中间打开另一个具有更大宽度和高度的盒子。 这是包含示例的页面:

http://wowbox.yolasite.com/

首先打开图像,然后打开div,你会看到我的意思。 div不是居中的。 但是当你关闭并重新打开div时,它会居中,因为当你单击WowBox链接时会发生.center()。 我只需要它始终处于中心位置,并且永远不会像那样陷入困境。

这是我目前用来集中它的代码:

jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; } 

我想让它在窗口重新resize时保持居中。 我也想把它放在盒子的宽度变宽,高度变高的地方,它会重新居中。 现在它不能正常工作。

有人可以帮忙吗?

提前致谢,

弥敦道

尝试使用您已有的示例代码。 为了澄清:

 jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; } $(document).ready(function(){ $('.element').center(); window.onresize = function(event) { $('.element').center(); } }); 

—————– 这有效———————

CSS

  .box{ width:200px; top:-5px; position:relative; background:#444; } .inner { height:0px; width:0px; background:#444; top:50%; left:50%; right:50%; bottom:50%; position:relative; } 

.outer {身高:200px; 宽度:400像素; 边框:2px点缀红色; }

HTML

 
wpfw efuiweh fuiwehf weuifh weuifh fuihwe fuihwefuiweh uwehf iuwehf uiwefhweuifh weuifhwe fuiweh fuiwehfuiwefh uiwefh weuifh weuifh weuifhwe uifh weuifhwefuiweh fuiweh fuiwehf iweufh weuih

jQuery的

 $(function(){ $(".box").css('top',-($(".box").height()/2)); $(".box").css('left',-($(".box").width()/2)); }); 

如果那不符合您的要求,请告诉我。 您甚至可以在http://jsfiddle.net/mazlix/m4Ttk/2/上看到,调整内部我们的外部div仍将保持居中。

适用于固定尺寸的例子http://jsfiddle.net/expert/vh2vy/5/