2017-09-11 20 views
0

我想调整一个基于其中包含的图像的宽度的div的大小,但没有JS方法来抓取图片的宽度似乎一直运行。.offsetWidth,.width,.width()等并不总是正确返回自动调整大小的元素

<div class="main_image"> 
    <img class="wp-post-image" src=""> 
    <label>label here</label> 
</div> 

img { 
    width: auto; 
    height: auto; 
    max-width: 500px; 
    max-height: 450px; 
} 

var newWidth = document.getElementsByClassName("wp-post-image"[0].offsetWidth; 
$(".wp-post-image").parent(".main_image").css({"width": newWidth}); 

我试着.style.width.width.offsetWidth.width().outerWidth().getBoundingClientRect.width()对于这些,它正确地抓住图像宽度一定的时间,但其他时候,它具有图像的宽度为0。 (或2,因为它有一个1px的边框,这是唯一的部分得到拾起,同样的交易。)问题是肯定抓住的宽度,而不是设置,通过警报测试。

我需要调整这个div的大小的原因是,如果图像标题比图像本身更宽,那么图像标题会自动换行。

有什么明显的我失踪了,要么是这种情况发生的原因,要么是解决我的问题的更好方法?

谢谢!

+0

您是否正在为您的控制台错误提供jQuery或JavaScript? – Brian

回答

1

我相信问题是您的图像必须在大小设置之前加载。你的JS正在执行之前,但不可靠。尝试设置大小之前,请尝试等待图像完成加载:

$('img').on('load', function() { 
    var newWidth = $(".wp-post-image").first().width(); 
    $(".wp-post-image").parent(".main_image").css("width", newWidth); 
}); 
+0

这就是问题所在!欣赏它。 – user8539669

相关问题