简体   繁体   English

获取图像高度以计算外部div的高度

[英]Get image height to calculate height of outer div

I'm trying to get the dynamic height of an image to add the corresponding css to it's parent div and another following div. 我正在尝试获取图像的动态高度,以将相应的css添加到它的父div和另一个div之后。

My js looks like this at the moment: 我的js目前看起来像这样:

  $(".imgContainer img").load(function(){
      var imageHeight = $(this).height();
      console.log(imageHeight);
      $(".parentDiv").css('min-height',imageHeight);
      $(".parentDiv .anotherDiv").css('height',imageHeight);
  });

  $(window).resize(function() {
      var imageHeight = $(".imgContainer img").height();
      $(".parentDiv").css('min-height',imageHeight);
      $(".parentDiv .anotherDiv").css('height',imageHeight);
  });

But: Every 2 to 3 times the height is not right or not loading properly. 但是:每2到3倍的高度是不对的或没有正确加载。 That means I'm not getting the img height in the variable just before I can add it via css. 这意味着我通过css添加它之前,我没有在变量中获得img高度。 I'm just having the wrong value in my console. 我只是在我的控制台中有错误的值。

It always works on resize. 它始终适用于调整大小。

Just in case, that's my html: 以防万一,这是我的HTML:

<div class="parentDiv">
    <div class="imgContainer">
        <img src="test.jpg" />
    </div>
    <div class="anotherDiv"></div>
</div>

Thanks for your help. 谢谢你的帮助。 Cara 卡拉

The problem seems to be caused by .load() method. 问题似乎是由.load()方法引起的。

I made this fiddle and it's working. 我做了这个小提琴 ,它正在发挥作用。

Note: .load() is deprecated see this 注: .load()已弃用看到

Caveats of the load event when used with images 与图像一起使用时加载事件的注意事项

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. 开发人员尝试使用.load()快捷方式解决的常见挑战是在图像(或图像集合)完全加载时执行函数。 There are several known caveats with this that should be noted. 应该注意有几个已知的警告。 These are: 这些是:

It doesn't work consistently nor reliably cross-browser It doesn't fire correctly in WebKit if the image src is set to the same src as before It doesn't correctly bubble up the DOM tree Can cease to fire for images that already live in the browser's cache 如果图像src设置为与之前相同的src它不能一致地工作也不能可靠地跨浏览器它在WebKit中无法正确触发它没有正确地冒泡DOM树可以停止为已经存在的图像触发在浏览器的缓存中

Use .on("load", function) instead of .load(function) , like follow: 使用.on("load", function)代替.load(function) ,如下所示:

$(".imgContainer img").on("load",function(){
      var imageHeight = $(this).height();
      $(".parentDiv").css('min-height',imageHeight);
      $(".parentDiv .anotherDiv").css('height',imageHeight);
      $(".result").html("Image height: " + imageHeight);
  });

I hope it helps you. 我希望它对你有所帮助。 Bye 再见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM