.offsetWidth,.width,.width()等并不总是在自动调整的元素上正确返回 [英] .offsetWidth, .width, .width() etc. not always returning properly on auto-sized element

查看:330
本文介绍了.offsetWidth,.width,.width()等并不总是在自动调整的元素上正确返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据其中包含的图像的宽度来调整div的大小,但没有任何用于抓取图像宽度的JS方法似乎始终如一。

 < div class =main_image> 
< img class =wp-post-imagesrc =>
< label>标签在这里< / 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()函数(){
var newWidth = $(。wp-post-image)。first()。width();
$(。wp-post-image)。 parent(。main_image)。css(width,newWidth);
});


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!

解决方案

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

这篇关于.offsetWidth,.width,.width()等并不总是在自动调整的元素上正确返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆