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


当前回答

我将使用jQuery UI位置函数。

见工作演示。

<div id="test" style="position:absolute;background-color:blue;color:white">
    test div to center in window
</div>

如果我有一个id“test”的div居中,那么下面的脚本将在文档准备的窗口中居中div。(位置选项中“my”和“at”的默认值为“center”)

<script type="text/javascript">
$(function(){
  $("#test").position({
     of: $(window)
  });
};
</script>

其他回答

我会推荐jQueryUI位置实用工具

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

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

请使用这个:

$(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();

我在扩展@TonyL给出的精彩答案。我添加了Math.abs()来包装值,而且我还考虑到jQuery可能处于“无冲突”模式,例如在WordPress中。

I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.

我做的另一件事是通过缓存$(window)对象来加快速度,这样我就减少了额外的DOM遍历,并且我使用了集群CSS。

jQuery.fn.center = function ($) {
  var w = $(window);
  this.css({
    'position':'absolute',
    'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
    'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
  });
  return this;
}

要使用,你可以这样做:

jQuery(document).ready(function($){
  $('#myelem').center();
});

我想纠正一个问题。

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

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

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

600 - 650 = -50  

-50 / 2 = -25

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

你可以使用CSS translate属性:

position: absolute;
transform: translate(-50%, -50%);

阅读这篇文章了解更多细节。