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


当前回答

这可以只用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 > < /身体>

其他回答

我会推荐jQueryUI位置实用工具

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

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

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

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

这太棒了。我添加了一个回调函数

center: function (options, callback) {

if (options.transition > 0) {
   $(this).animate(props, options.transition, callback);
} else { 
    $(this).css(props);
   if (typeof callback == 'function') { // make sure the callback is a function
       callback.call(this); // brings the scope to the callback
   }
}

你可以使用CSS translate属性:

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

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

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