我如何去设置一个<div>在屏幕的中心使用jQuery?


当前回答

这是我的尝试。我最终在我的Lightbox克隆版本中使用了它。这种解决方案的主要优点是,即使窗口大小被调整,元素也会自动保持居中,这是这种用法的理想选择。

$.fn.center = function() {
    this.css({
        'position': 'fixed',
        'left': '50%',
        'top': '50%'
    });
    this.css({
        'margin-left': -this.outerWidth() / 2 + 'px',
        'margin-top': -this.outerHeight() / 2 + 'px'
    });

    return this;
}

其他回答

我会推荐jQueryUI位置实用工具

$('your-selector').position({
    of: $(window)
});

这给了你更多的可能性,而不仅仅是定心…

我想纠正一个问题。

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

以上代码在这种情况下将不起作用。height(假设用户调整屏幕大小,内容是动态的)和scrollTop() = 0,示例:

窗口。高度是600 这一点。高度是650

600 - 650 = -50  

-50 / 2 = -25

现在方框在屏幕外的中心位置为-25。

请使用这个:

$(window).resize(function(){
    $('.className').css({
        position:'absolute',
        left: ($(window).width() - $('.className').outerWidth())/2,
        top: ($(window).height() - $('.className').outerHeight())/2
    });
});

// To initially run the function:
$(window).resize();

之所以会出现这种糟糕的过渡,是因为每次滚动文档时都要调整元素的位置。你想要的是使用固定的定位。我尝试了上面列出的固定中心插件,这似乎解决了这个问题很好。固定定位允许您将一个元素居中一次,CSS属性将在您每次滚动时为您维护该位置。

我喜欢添加函数到jQuery,所以这个函数会有帮助:

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

现在我们可以写成:

$(element).center();

演示:小提琴(添加参数)