2011-07-09 22 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'のサイズはどうなるでしょうか? –

+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

@Jack:ありがとうジャック!明らかに、私は新しいユーザーであり、これはstackoverflowの私の最初の投稿です。 :D –