jQuery更改图像大小和包含Div

时间:2011-04-20 14:29:55

标签: jquery image size caption

我有一个图片包装器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);
       })
     })
   })
});

2 个答案:

答案 0 :(得分: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 */});
  });
});

答案 1 :(得分: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),然后立即尝试获取其尺寸,而不首先检查图像是否已完成加载。

看起来这个问题可能有助于引导您朝着正确的方向前进:

How can I determine if an image has loaded, using Javascript/jQuery?