function appData (arg) {
var tmp ='<div class="eventPopUp" z-index:6;">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>'
$(arg).html(tmp);
var off= $(tmp).offset().left;
var wid = $(tmp).width();
//var hei = $(arg).children().height();
var hei = $(tmp).outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
您好在上面的函数中我正在创建一个包含html元素的变量,我想知道tmp变量的height
和width
(因为内容会动态更新)我的问题是我可以使用width
方法获取变量tmp的width()
,并使用height
方法获取height()
0。请帮我找一下var tmp
的高度。如果我通过使用样式明确地给出高度,那么height()方法给出了正确的答案,arg是'li',我追加了这个变量。
答案 0 :(得分:2)
jQuery似乎很混淆你在做$(tmp)
时确切选择了哪个元素,因此返回一个空高度。
如果在初始化时明确将字符串定义为对象,则可以在将高度附加到DOM后计算高度。试试这个:
function appData(arg) {
var $tmp = $('<div class="eventPopUp">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>')
$(arg).append($tmp);
var off = $tmp.offset().left;
var wid = $tmp.width();
var hei = $tmp.outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
答案 1 :(得分:0)
你获得0的原因很可能是因为你在元素中包含任何内容之前正在读取高度。换句话说,请尝试使用document ready
$( document ).ready(function() {
// call appData function here
});
如果这不起作用,请尝试使用setTimeout
x = setTimeout(function() {
// call appData or read height and if height of my selection is != 0 then
// {
// clearTimeout(x);
// myHeight = height of my selection
// call function that does something with it and send it as a param
// }
}, 1000);
你每隔一秒检查一次身高,直到身高不同于0.这是一个黑客,我不推荐它,除非你开始在墙上留下额头痕迹。