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


当前回答

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

其他回答

请使用这个:

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

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

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

工作示例

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

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

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

我不认为有一个绝对位置将是最好的,如果你想要一个元素总是居中在页面的中间。你可能需要一个固定的元素。我发现另一个jquery定心插件使用固定定位。这叫做固定中心。

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