提问者:小点点

如何将对话框定位到窗口的中心


有人能告诉我如何使用JQuery将一个框定位到窗口的中心吗。我将在下面粘贴代码:-

    

    $("#address_book").click(function (e)
      {
          .........

         ShowDialog(false);
         e.preventDefault();
        ........
      });

    function ShowDialog(modal){

    ....  
      $("#overlay").show();

      $("#dialog").fadeIn(300);

      if (modal)
      {

         $("#overlay").unbind("click");
      }
      else
      {
         $("#overlay").click(function (e)
         {
            HideDialog();
         });
      }
     }
    

我希望对话框位于窗口的中心。有人能告诉我怎么做吗


共3个答案

匿名用户

下面的代码不是jQuery,而是纯javascript,所以它将在没有任何hickup的情况下工作

  var dialog = document.getElementById('dialog')
  dialog.style.top = ((window.innerHeight/2) - (dialog.offsetHeight/2))+'px';
  dialog.style.left = ((window.innerWidth/2) - (dialog.offsetWidth/2))+'px';

同样的代码使用jquery

  $('#dialog').css({
      top: ((window.innerHeight/2) - ($('#dialog').height()/2))+'px',
      left:((window.innerWidth/2) - ($('#dialog').width()/2))+'px'
    });

演示的代码,在不同的应用程序Demo

注意:为了定位该div,您的#对话框的css中应该有,position:absolute

匿名用户

jQueryUI对话框自动居中,只要您在打开之前已将所有内容放置在其中。

但是,它们将始终相对于浏览器窗口居中,而不是任何父“容器”元素,因为jQueryUI将从DOM中删除转换为对话框的元素,并将其重新附加到文档中。正文

匿名用户

在jQuery中尝试以下操作:

$("#dialog").css("margin-top", ($(document.height() - $(this).height())/2);
$("#dialog").css("margin-left", ($(document.width() - $(this).width())/2);

这应该行得通。