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


当前回答

这个功能的转换组件在Chrome中工作得非常糟糕(没有在其他地方测试)。我会调整窗口的大小,我的元素会慢慢移动,试图赶上。

因此下面的函数注释了这一部分。此外,我还添加了参数,用于传入可选的x和y布尔值,如果你想垂直居中,而不是水平居中,例如:

// Center an element on the screen
(function($){
  $.fn.extend({
    center: function (x,y) {
      // var options =  $.extend({transition:300, minX:0, minY:0}, options);
      return this.each(function() {
                if (x == undefined) {
                    x = true;
                }
                if (y == undefined) {
                    y = true;
                }
                var $this = $(this);
                var $window = $(window);
                $this.css({
                    position: "absolute",
                });
                if (x) {
                    var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
                    $this.css('left',left)
                }
                if (!y == false) {
            var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();   
                    $this.css('top',top);
                }
        // $(this).animate({
        //   top: (top > options.minY ? top : options.minY)+'px',
        //   left: (left > options.minX ? left : options.minX)+'px'
        // }, options.transition);
        return $(this);
      });
    }
  });
})(jQuery);

其他回答

我用这个把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'
});

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

通常,我只会用CSS做这个…但是既然你问你一个方法来做这个用jQuery…

下面的代码将一个div在其容器内水平和垂直地居中:

$("#target").addClass("centered-content") .wrap("<div class='center-outer-container'></div>") .wrap("<div class='center-inner-container'></div>"); body { margin : 0; background: #ccc; } .center-outer-container { position : absolute; display: table; width: 100%; height: 100%; } .center-inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding : 20px; border : 1px solid #000; } <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <div id="target">Center this!</div>

(也可以参看这把小提琴)

这是我的版本。看完这些例子后,我可能会改变它。

$.fn.pixels = function(property){
    return parseInt(this.css(property));
};

$.fn.center = function(){
    var w = $($w);
    return this.each(function(){
        $(this).css("position","absolute");
        $(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
        $(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
    });
};

请使用这个:

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