简体   繁体   中英

Centering a floating div with jQuery

I have just inherited some code and part of that code is to show a floating div and center it.

Here is the code:

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');
}

In its defense, it works perfectly but I the following lines look like a hack:

  width = width + offsetY;

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

Is there a better and neater way of getting the same result than this.

The question seems to have an awful lot of code to do what I thought was relatively simple. Live example: 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'});

There are many ways to centre a floating div, the example youve given isnt perhaps the best way but it resembles one of the ways you can do it in pure css.

Here is a good link with a little more info on it. http://blog.themeforest.net/tutorials/vertical-centering-with-css/

Using

margin-left:auto;
margin-right:auto;

will set it horizontally centred

I imagine those subtractions are to take half the width and height of the element to be centered. To make this dynamic you just need to replace that with the value of half of the width and height of the element to be positioned.

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

Then you don't need to subtract anything from the overall height and width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM