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


当前回答

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

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
   }
}

其他回答

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

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

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

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

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

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
   }
}