2

我试图在屏幕上居中一个模态窗口(这工作完全正常),除了当我通过 jQuery 向它添加内容然后让它的宽度和高度居中时,它总是会输出高度0而不是它预期高度。这是我的代码:

        // Now to use the Data and add it to the Modal Window...
        $('#portfolioModal .inner .data').html('<h1>' + parsedData['name'] + '</h1>\n' + parsedData['desc'] + '');

        var modalWidth = $('#portfolioModal').width(); // Get the Modal Window's Width
        var modalHeight = $('#portfolioModal').height(); // Get the Modal Window's Height

        alert(modalHeight);

        var left = (windowWidth / 2) - (modalWidth / 2); // Calculate the left margin for center alignment
        var top = (windowHeight / 2) - (modalHeight / 2); // And calculate the top margin for center alignment

        $('#portfolioModal').css({ // Append the Left and Top margin to the Modal Window
            'left': left,
            'top': top
        });

模态 HTML:

        <div id="portfolioMask">
                    <div id="portfolioModal">
                                <div class="inner">
                                            <div id="portfolioModalClose">Close</div>
                                            <span class="data"></span>
                                </div>
                    </div>
        </div>

任何帮助表示赞赏!

4

4 回答 4

1

如果 divdisplay:none在您触发 jQuery height() 时被隐藏() - 它总是返回 0 的高度。我相信这是因为它实际上并没有占用您页面上的空间 - 这意味着它实际上不是它的一部分正在显示。如果您想保持 div 隐藏,但想获得高度,我建议使用以下 CSS:

position:absolute;
visibility: hidden;

使用隐藏可见性将使元素占用 dom 中的空间,但使其不可见-因此它将具有高度。使用绝对位置会将其从您的实际页面中弹出,因此它不会强制页面上的内容被其高度/宽度推动。

我个人也喜欢加一个

left: -30000px;

我发现一些较旧的 IE 不能很好地解决这个问题,并且将 div 从页面上浮动确保它们不可见。

于 2012-11-27T16:02:29.953 回答
0

试试 $('#portfolioModal').css('height');

更新:

// Now to use the Data and add it to the Modal Window...
$('#portfolioModal .inner .data').append('<h1>' + parsedData['name'] + '</h1>\n' + parsedData['desc'] + '', function(){
  var modalWidth = $('#portfolioModal').width(); // Get the Modal Window's Width
  var modalHeight = $('#portfolioModal').height(); // Get the Modal Window's Height

  alert(modalHeight);

  var left = (windowWidth / 2) - (modalWidth / 2); // Calculate the left margin for center alignment
  var top = (windowHeight / 2) - (modalHeight / 2); // And calculate the top margin for center alignment

  $('#portfolioModal').css({ // Append the Left and Top margin to the Modal Window
      'left': left,
      'top': top
  });

});
于 2012-11-27T15:10:23.313 回答
0

您必须在 left 和 top 变量中指定像素。

var left = (1024 / 2) - (modalWidth / 2) + "px"; 
var top = (768 / 2) - (modalHeight / 2) + "px"; 

$('#portfolioModal').css({ 
   'margin-left': left,
   'margin-top': top
 });
于 2012-11-27T16:11:46.853 回答
0

对话框是否在 div 中?如果它是一个跨度,它将始终返回 0。

于 2012-11-27T15:12:41.273 回答