【问题标题】:.offsetWidth, .width, .width() etc. not always returning properly on auto-sized element.offsetWidth、.width、.width() 等并不总是在自动调整大小的元素上正确返回
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 这就是问题所在!欣赏它。
猜你喜欢
  • 2014-01-23
  • 2012-11-12
  • 2011-09-19
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多