使用 jQuery 将浮动 div 居中

dag*_*da1 0 javascript css jquery

我刚刚继承了一些代码,该代码的一部分是显示一个浮动 div 并将其居中。

这是代码:

function showFloatingDialog(element) {
  removeMessage();
  var height, width;
  var offsetY = $(document).scrollTop();

  if (offsetY == undefined) {
    offsetY = 0;
  }

  var dialog = $('#' + element);

  dialog.show();

  height = (($(window).width() - dialog.width()) / 2);
  width = ($(window).height() - dialog.height()) / 2;
  width = width + offsetY;

  height = height - 195;
  width = width - 130;

  dialog.css('position', 'absolute');
  dialog.css('left', height + 'px');
  dialog.css('top', width + 'px');
}
Run Code Online (Sandbox Code Playgroud)

在它的辩护中,它工作得很好,但我下面的几行看起来像是一个黑客:

  width = width + offsetY;

  height = height - 195;
  width = width - 130;
Run Code Online (Sandbox Code Playgroud)

有没有比这更好、更简洁的方法来获得相同的结果。

tw1*_*w16 5

这个问题似乎有大量的代码来完成我认为相对简单的事情。实例: http: //jsfiddle.net/LHSDU/1/

var width = ($(window).width() - dialog.width()) / 2;
var height = ($(window).height() - dialog.height()) / 2;

dialog.css({'position' : 'absolute' , 'left' : width + 'px', 'top' : height + 'px'});
Run Code Online (Sandbox Code Playgroud)