如何获取内部动态加载图像的元素的高度

How to get height of element with dynamically loaded images inside

本文关键字:图像 加载 元素 高度 动态 内部 何获取 获取      更新时间:2024-03-12

nbsp nbsp 我有很多表,在最后一个tr的最后一个td中,我放了来自后端的消息。不仅可以有文本,还可以有图像(标签中的url),所以它们是动态加载的。我需要得到这张桌子的高度,如果超过400,我会添加一些污染物。

 nbsp nbsp;首先,我做了这个:

$("table[name]='forum'").each(function() {
        var height = $(this).height();
        if (height > 400) {
            var redirect = $("#backUrl").val() + "#" + $(this).find("[name]='answ'").attr("id");
            $(this).find("tr:last-child > td:last-child").append(function() {
                return "<div></div><a style='float: right' href='"+ redirect + "'><img src='/images/arrow_up.png'></a>";
            });
        };
    });

 nbsp nbsp;但它不适用于带有图像的表。然后我在谷歌上搜索了img,我应该使用load()并添加:

$(this+"> img").load(function() {
     height += $(this).height(); 
});

但我理解,这是错误的,因为img可以在这个块完成后加载。我做了一些其他的动作,但不会影响到我想要的效果。

 nbsp nbsp<这个问题的解决办法是什么?因为它在没有img标记的情况下计算整个元素的高度>

要获得最终的表格高度(如果img会影响高度,或者您可以预先设置一些最大高度),您必须等待加载所有图像。

var table = $(this), imgs = table.find("img"), len = imgs.length;
imgs.one('load', function() {
    len--;
    //now all image loaded
    if (len == 0) {
        //here you got the final height
        height = table .height();
        //do stuffs here
    }
}).each(function() {
    if (this.complete)
        $(this).load();
});
$(this).find("img").load(function() {
     height += $(this).height(); 
});