也以调整大小为中心 [英] center on resize too
问题描述
这有效:
$.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();
..但是如果调整窗口大小,元素将保持在相同位置,我如何也将其与调整大小居中?
.. but the element stays in the same position if the window is resized, how do I center it with the resize too?
谢谢
推荐答案
您需要在window
resize 事件中执行该代码.但是,如果调整浏览器的大小,则将触发该事件!因此,通常创建一个小的平衡器"是一个好主意.
You would need to execute that code in the window
resize event. But, if the browser is resized this event fires huge! So it's in general a good idea to create a little "balancer".
$(window).bind('resize', function() {
var that = this;
if(!('balancer' in that) ) {
that.balancer = setTimeout(function() {
$('#container').center();
delete that.balancer;
}, 200);
}
});
这将吸收调整浏览器窗口大小时触发的许多事件.实际上,它仅在最长200ms内调用.center()
.您甚至应该增加该值,并将节点引用缓存到#container
元素.
This will absorb the many events that are fired when resizing the browser window. In fact, it only calls the .center()
at a maximum of 200ms. You probably should even increase that value and cache the node reference to the #container
element.
这篇关于也以调整大小为中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!