【发布时间】:2018-02-20 03:24:45
【问题描述】:
我正在尝试根据包含在其中的图像的宽度调整 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 大小的原因是,如果图片标题比图片本身宽,图片标题会自动换行。
有什么明显的我遗漏的东西,要么是发生这种情况的原因,要么是解决我的问题的更好方法?
谢谢!
【问题讨论】:
-
您的 jQuery 或 javascript 中是否出现控制台错误?
标签: javascript jquery html width