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


当前回答

我在扩展@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();
});

其他回答

我在扩展@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();
});

我用这个:

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});

我喜欢添加函数到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();

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

我用这个把UL放在中间位置。

cadasWidth          = $('.card-dashboard').innerWidth();
cadasWidthCenter    = cadasWidth/2;

ulmenuWidth         = $('.card-dashboard ul#menu').outerWidth();
ulmenuWidthCenter   = ulmenuWidth/2;

ulmenuStart = cadasWidthCenter - ulmenuWidthCenter;

$('.card-dashboard ul#menu').css({
    'left' : ulmenuStart,
    'position' : 'relative'
});

我这里有一个“居中”方法,它确保你试图居中的元素不仅是“固定的”或“绝对的”定位,而且它还确保你正在居中的元素小于它的父元素,这个居中和元素相对于它的父元素,如果元素的父元素小于元素本身,它将从DOM中抓取到下一个父元素,并相对于它居中。

$.fn.center = function () {
        /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>

        var element = $(this),
            elementPos = element.css('position'),
            elementParent = $(element.parent()),
            elementWidth = element.outerWidth(),
            parentWidth = elementParent.width();

        if (parentWidth <= elementWidth) {
            elementParent = $(elementParent.parent());
            parentWidth = elementParent.width();
        }

        if (elementPos === "absolute" || elementPos === "fixed") {
            element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
        }
    };