1

我有一个div包含图像和标题的图像包装器。

使用以下图像包装器div的大小调整为图像的宽度:

$('.imgright').each(function(){
    $(this).width($(this).find('img').outerWidth());
});

div如果依赖于父类,我也希望使用不同的图像路径。以下作品:

$('.grid_12').each(function(){
    $(this).find('img').each(function(){
        $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    });
});

但将这些放在一起并不总是设置图像包装的宽度div

$('.grid_12').each(function(){
    $(this).find('img').each(function(){
        $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    });
});
$('.imgright').each(function(){
    $(this).width($(this).find('img').outerWidth());
});

有什么建议么?

感谢 2 个非常快速的答案,我已经重组了我的代码并使用该.load()函数来获取更改后的图像细节。

工作代码是:

$('.grid_12').each(function(){
   $(this).find('img').each(function(){
     $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
     $(this).load(function(args){
       var newWidth = $(this).outerWidth();
       $(this).parent('.imgright').each(function(){
         $(this).width(newWidth);
       })
     })
   })
});
4

2 回答 2

0

会不会是图片还没加载?您可以在更改 ImagePath 时向图像添加负载处理程序

$('.grid_12').each(function(){
  $(this).find('img').each(function(){
    $(this).attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
    $(this).load(function(args){/* find the parent div and change size */});
  });
});
于 2011-04-20T14:38:59.033 回答
0

对于初学者,您可以利用链接使您的代码更简洁:

$('.grid_12').each(function(){
    $(this)
        .find('img')
            .each(function(){
                $(this)
                      .attr("src", $(this).attr('src').replace('/StandardImage/','/MidSizeImage/')); 
            })
            .end()
        .width($(this).find('img').outerWidth());
});

现在,至于您的问题,正在发生的事情是您正在加载图像(通过更改它的 src),然后立即尝试获取其尺寸,而无需先检查图像是否已完成加载。

看起来这个问题可能会帮助您朝着正确的方向前进:

如何使用 Javascript/jQuery 确定图像是否已加载?

于 2011-04-20T14:41:03.363 回答