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


当前回答

有很多方法可以做到。我的对象被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;
    };

其他回答

我用这个:

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

这可以只用CSS来完成。但他们是用jQuery或JavaScript问的

在这里,使用CSS Flex box属性来对齐div中心。

body.center{
  display:flex;
  align-items:center; // Vertical alignment
  justify-content:center; // Horizontal alignment
}

对齐项目:中心;-用于垂直对齐。

justify-content:中心;-用于水平对齐。

document.querySelector .classList.add(“身体”)(“中心”); 身体{ Margin: 0; 身高:100 vh; 宽度:100%; 背景:# ccc; } #{主要 背景:# 00 cc00; 宽度:100 px; 身高:100 px; } body.center { 显示:flex; 对齐项目:中心; justify-content:中心; } <身体> < div id = "主" > < / 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");
    });
};

我在这里放了一个jquery插件

非常短的版本

$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});

短的版本

(function($){
    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).outerHeight()) / 2;
                var left = ($(window).width() - $(this).outerWidth()) / 2;
                $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
            });
        }
    }); 
})(jQuery);

由以下代码激活:

$('#mainDiv').center();

插件版本

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

由以下代码激活:

$(document).ready(function(){
    $('#mainDiv').center();
    $(window).bind('resize', function() {
        $('#mainDiv').center({transition:300});
    });
);

对吗?

更新:

从css技巧

.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); /* Yep! */
  width: 48%;
  height: 59%;
}

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