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


当前回答

这是未经测试的,但类似的东西应该工作。

var myElement = $('#myElement');
myElement.css({
    position: 'absolute',
    left: '50%',
    'margin-left': 0 - (myElement.width() / 2)
});

其他回答

有很多方法可以做到。我的对象被display:none隐藏在BODY标签中,以便定位相对于BODY。在使用$ (" # object_id”),告诉(),我叫美元(“# object_id”).center ()

我使用position:absolute,因为这是可能的,特别是在一个小型移动设备上,模式窗口比设备窗口大,在这种情况下,如果定位是固定的,一些模式内容可能是不可访问的。

以下是根据其他人的回答和我的具体需求我的口味:

$.fn.center = function () {
        this.css("position","absolute");

        //use % so that modal window will adjust with browser resizing
        this.css("top","50%");
        this.css("left","50%");

        //use negative margin to center
        this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
        this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");

        //catch cases where object would be offscreen
        if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
        if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});

        return this;
    };

这个功能的转换组件在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);

为了使元素相对于浏览器视窗居中,不要使用position: absolute,正确的位置值应该是固定的(absolute的意思是:“元素的位置相对于它的第一个定位(不是静态的)祖先元素”)。

这个中心插件的替代版本使用“%”而不是“px”,所以当你调整窗口大小时,内容保持居中:

$.fn.center = function () {
    var heightRatio = ($(window).height() != 0) 
            ? this.outerHeight() / $(window).height() : 1;
    var widthRatio = ($(window).width() != 0) 
            ? this.outerWidth() / $(window).width() : 1;

    this.css({
        position: 'fixed',
        margin: 0,
        top: (50*(1-heightRatio)) + "%",
        left: (50*(1-widthRatio))  + "%"
    });

    return this;
}

你需要把margin: 0从宽度/高度中排除内容边距(因为我们使用的是位置固定,有边距没有意义)。 根据jQuery文档使用. outerwidth (true)应该包括边缘,但当我在Chrome中尝试时,它没有像预期的那样工作。

50*(1比)来自:

窗口宽度:W = 100%

元素宽度(%):w = 100 * elementWidthInPixels/windowWidthInPixels

它们计算左边居中:

 left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
 = 50 * (1-elementWidthInPixels/windowWidthInPixels)

你可以像这样单独使用CSS居中:

工作示例

.center { 位置:绝对的; 高度:50 px; 宽度:50 px; 背景:红色; 顶部:calc(50% - 50px/2);/*高度除以2*/ 左:calc(50% - 50px/2);/*宽度除以2*/ } < div class = "中心" > < / div >

Calc()允许您在css中进行基本计算。

用于calc()的MDN文档 浏览器支持表

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

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