2011-04-12 48 views
0

这工作:中心调整大小过于

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

..但该元素停留在相同的位置,如果窗口大小,我该如何与调整大小过于居中?

感谢

回答

1

您需要在window执行该代码调整事件。但是,如果浏览器被重新调整大小,这个事件就会激化!因此,创建一个“平衡器”通常是一个好主意。

$(window).bind('resize', function() { 
    var that = this;   

    if(!('balancer' in that)) { 
     that.balancer = setTimeout(function() { 
      $('#container').center(); 
      delete that.balancer; 
     }, 200); 
    } 
}); 

这将吸收调整浏览器窗口大小时触发的许多事件。实际上,它只能在最长200ms时调用.center()。您甚至应该增加该值并将节点引用缓存到#container元素。

0

编辑 ::

捐赠百分比topleft可以把在中心。但是这个糟糕......真的很糟糕。

$.fn.center = function() { 
     $(this).css({'position': 'absolute', 
        'top': '40%', 
        'left': '40%' 
        }); 
    }; 

    $(function(){ 
     $('#container').center(); 
    }) 

jsfiddle