.offsetWidth、.width、.width() 等并不总是在 auto-sized 元素上正确返回

.offsetWidth, .width, .width() etc. not always returning properly on auto-sized element

我正在尝试根据其中包含的图像的宽度调整 div 的大小,但是没有任何一种用于抓取图像宽度的 JS 方法似乎一直有效。

<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 大小的原因是,如果图像标题比图像本身宽,图像标题将换行。

有没有什么明显的我遗漏的东西,或者是发生这种情况的原因,或者是解决我的问题的更好方法?

谢谢!

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

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