jQuery .height()无法正常运行

时间:2012-11-27 15:08:34

标签: javascript jquery

我试图将一个模态窗口集中在屏幕上(它工作得很好),除了我通过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 个答案:

答案 0 :(得分:1)

如果在激活jQuery height()时隐藏div(display:none) - 它将始终返回高度0.我相信这是因为它实际上没有占用页面上的空间 - 这意味着没有展示它就不是它的一部分。如果你想隐藏div,但想要获得高度,我建议使用以下CSS:

position:absolute;
visibility: hidden;

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

我个人也想添加一个

left: -30000px;

我发现一些较旧的IE浏览器不能很好地完成这项工作,并将div从页面上移开,确保它们不可见。

答案 1 :(得分:0)

尝试$(&#39;#portfolioModal&#39;)。css(&#39; height&#39;);

更新

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

});

答案 2 :(得分:0)

是div中的对话框吗?如果它是一个跨度,它将始终返回0.

答案 3 :(得分:0)

您必须在左侧和顶部变量中指定像素。

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

$('#portfolioModal').css({ 
   'margin-left': left,
   'margin-top': top
 });
相关问题