简体   繁体   English

使用js offsetHeight获取包含图像的div的高度

[英]Get height of div containing image with js offsetHeight

I'm trying to get the height of a div containing a headline and an image. 我正在尝试获取包含标题和图像的div的高度。 All I get back is the height of the heading. 我得到的只是标题的高度。 If I add a specific height to the container div I get the correct height (in this case 300px), but I need the different heights. 如果将特定高度添加到容器div中,则可以得到正确的高度(在这种情况下为300px),但是我需要不同的高度。 Thx for any help! 感谢您的帮助!

My js code: 我的js代码:

var tile1 = document.getElementById('t1').offsetHeight;

My HTML: 我的HTML:

<div class="t" id="t1" style="height:300px !important;">
   <article>
      <header class="beitrag">
         <div class="beitrag-meta">Date: 2016-11-02 19:59:45</div>
      </header>
      <div class="beitrag-inhalt"><img src="219594520163877.jpg" ></div>
  </article>
</div>

Make sure you run it after the page has been loaded. 确保在页面加载后运行它。

Stack snippet 堆栈片段

 window.addEventListener('load', function() { var tile1 = document.getElementById('t1').offsetHeight; console.log(tile1); }) 
 <div class="t" id="t1"> <article> <header class="beitrag"> <div class="beitrag-meta">Date: 2016-11-02 19:59:45</div> </header> <div class="beitrag-inhalt"><img src="http://placehold.it/100/"></div> </article> </div> 

Or with a script tag at the bottom of the body 或者在body底部带有脚本标签

Stack snippet 堆栈片段

 <div class="t" id="t1"> <article> <header class="beitrag"> <div class="beitrag-meta">Date: 2016-11-02 19:59:45</div> </header> <div class="beitrag-inhalt"><img src="http://placehold.it/100/"></div> </article> </div> <script> var tile1 = document.getElementById('t1').offsetHeight; console.log(tile1); </script> 

use jQuery load function 使用jQuery load功能

 $( document ).ready(function() { $("img").load(function() { var tile1 = document.getElementById('t1').clientHeight; alert("height: "+tile1); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="t" id="t1"> <article> <header class="beitrag"> <div class="beitrag-meta">Date: 2016-11-02 19:59:45</div> </header> <div class="beitrag-inhalt"><img src="http://placehold.it/300x350" ></div> </article> </div> 

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

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