将div或对话框定位到窗口的中心

4 jquery

我使用以下代码将对话框定位到窗口的中心.

var dialog = $('#dialogBox');
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var dHeight = $('#dialogBox').height();
var dWidth = $('#dialogBox').width();
$('#dialogBox').css({top:windowHeight/2 - dHeight/2, left:windowWidth/2 - dWidth/2}).show();
Run Code Online (Sandbox Code Playgroud)

它将div定位到窗口的中心.但我想将对话框定位到当前可见区域的中心.因此,即使我向下滚动或向上滚动,对话框也将位于窗口的中心.用jquery怎么做?

任何建议都会很有感激!

谢谢.

Sar*_*raz 7

你可以这样做以死为中心:

$('#elementID').css({
  position:'absolute',
  top:'50%',
  left:'50%',
  width:'600px',                 // adjust width
  height:'300px',                // adjust height
  zIndex:1000,
  marginTop:'-150px'             // half of height
  marginLeft:'-300px'            // half of width
});
Run Code Online (Sandbox Code Playgroud)

请注意,元素将出现在中心但滚动时不会移动.如果要使其显示在中心,则需要设置positionfixed.但是,这在IE6中不起作用.所以决定是你的:)


您还可以创建快速简单的jQuery插件:

(function($){
    $.fn.centerIt = function(settings){

        var opts = $.extend({}, $.fn.centerIt.defaults, settings);

        return this.each(function(settings){
          var options = $.extend({}, opts, $(this).data());
          var $this = $(this);

          $this.css({
            position:options.position,
            top:'50%',
            left:'50%',
            width:options.width,                 // adjust width
            height:options.height,               // adjust height
            zIndex:1000,
            marginTop:parseInt((options.height / 2), 10) + 'px'  // half of height
            marginLeft:parseInt((options.width / 2), 10) + 'px'  // half of height
          });

        });
    }

    // plugin defaults - added as a property on our plugin function
    $.fn.centerIt.defaults = {
      width: '600px',
      height: '600px',
      position:'absolute'
    }

})(jQuery);
Run Code Online (Sandbox Code Playgroud)

后来使用它像:

$('#elementId').centerIt({width:'400px', height:'200px'});
Run Code Online (Sandbox Code Playgroud)