2011-10-27 56 views
0

假设我有一个JS变量和我的HTML数据存储到它像通过jquery的确定高度和动态HTML元素的宽度

var data = '<div id="tst">here will be my othere html</div>' 

在这种情况下我能确定什么会是高度& DIV的宽度使用jQuery的tst?

一个人给我的解决方案就像

var $test = $(data).appendTo('body'); 
var size; 

window.setTimeout(function(){ 
size = { 
    height: $test.height(), 
    width: $test.width() 
}; 
$test.remove(); 
}); 

,但上面的代码看起来有点复杂。如果有人知道简单的解决方案,那么请给我一个示例代码来这样做。感谢

+1

你不需要使用'.setTimeOut()'。 –

回答

3

这段代码就足够了:

//put html from variable at the end of <body> 
var $test = $(data).appendTo('body'); 

//determine height and width and put into one variable for convenience 
var size = { 
    height: $test.outerHeight(), 
    width: $test.outerWidth() 
}; 

请注意,甚至没有必要使用size。你可以把它分成两个变量widthheight。这仅仅是个人喜好。

另请注意,我更喜欢使用.outerHeight().outerWidth(),因为常规的.width()/.height()不计算边框。这取决于你决定哪些是你真正需要的;)

-1

你能做到这一点

在文件准备的高度将是你从ID在这里定义它

$(document).ready(function() { 
$("#tst").css({'height' : '100px'}); 
});