2011-07-09 21 views
1

在jQuery中,我想在將其附加到主體之前獲取克隆對象的高度。獲取克隆對象的動態高度

注意:我沒有在CSS中指定寬度和高度(這是要求)。

可能嗎?

<body> 

<style>.square {}</style> 

<script> 
jQuery(function($) { 
    var o = $(".square").clone(true); 
    $(o).css('height','auto').html("Some stuff...<br/><br/>"); 

    // output 0 (Question: how to get the height?) 
    console.log($(o).height()); 

    $(o).appendTo("body"); 

    // output the height (i.e. 38) 
    console.log($(o).height()); 
}); 
</script> 
<div class="square"></div> 
</body> 
+0

你嘗試了嗎?沒有明確維度的空白'div'的大小_mean_? –

+0

如何獲得未放置在DOM中的東西的高度?它還沒有高度! –

+0

@傑克:這不完全正確。 –

回答

5

由於它們添加到文檔之前,你不能可靠計量的元素,一種方法是利用絕對定位把元素視之外:

jQuery(function($) { 
    var $o = $(".square").clone(true); 
    $o.css("height", "auto").html("Some stuff...<br/><br/>"); 

    $o.css({ 
     position: "absolute", 
     left: "-10000px" 
    }).appendTo("body"); 

    console.log($o.height());  // Works. 

    $o.css("position", "static"); // Reset positioning. 
}); 
+0

感謝您的解決方案!這真的有幫助! –

+0

@Ronald T如果這個解決方案的工作,你應該把它標記爲接受「點擊除了答案之外的勾號」:) –

+1

@傑克:謝謝傑克!很明顯,我是一個新用戶,這是我在stackoverflow中的第一篇文章。 :d –