center on resize too

↘锁芯ラ 提交于 2019-12-11 15:19:00

问题


This works:

$.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?

Thanks


回答1:


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);
    }
});

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.




回答2:


EDIT::

giving percentage to top and left can put at center. but this bad ... really really bad.

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

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

On jsfiddle.



来源:https://stackoverflow.com/questions/5634444/center-on-resize-too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!