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

你说的曾经没有我的故事 提交于 2019-12-11 15:35:20

问题


I'm trying to resize a div based on the width of an image contained within it, but no JS method for grabbing the image's width seems to be working consistently.

<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});

I've tried with .style.width, .width, .offsetWidth, .width(), .outerWidth(), .getBoundingClientRect.width() For each of these, it correctly grabs the image width some of the time, but other times it has the image's width as 0. (Or 2 because it has a 1px border and that's the only part getting picked up, same deal.) The issue is definitely the grabbing of the width, not the setting, as tested with alerts.

The reason I need to resize this div is so that the image caption will wrap if it's wider than the image itself.

Is there something obvious I'm missing, either a reason this is happening or a better way to solve my problem?

Thanks!


回答1:


I believe the issue is that your image has to load before the size is set. Your JS is executing before this happens, but not reliably. Try waiting for the image to finish loading before you attempt to set the size:

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


来源:https://stackoverflow.com/questions/46163270/offsetwidth-width-width-etc-not-always-returning-properly-on-auto-sized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!