Get the dynamic height of a clone object
In jQuery, I would like to get the height of a clone object BEFORE it is appended to the body.
Note: I didn't specify the width and height in CSS (this is the requirement).
Is it possible?
<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>
Since you cannot reliably measure elements before adding them to the document, one way is to take advantage of absolute positioning to put the element outside of the viewport:
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.
});
精彩评论