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


当前回答

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

其他回答

只是说: $ (" # divID ") . html ($ (") . html ($ (" # divID ") . html ()));

你可以像这样单独使用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();

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

通常,我只会用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>

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

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