简体   繁体   English

给定已知宽度计算div高度?

[英]Calculate div height given a known width?

I have a div that contains a picture and some text (the image is of the variable size and the text is of the variable length).我有一个包含图片和一些文本的 div(图像大小可变,文本长度可变)。
Is there any way to calculate the height required to fit all the div content, given that the exact width is predefined?考虑到确切的宽度是预定义的,有没有办法计算适合所有 div 内容所需的高度?

UPD getting same wrong result when using $(document).ready()使用$(document).ready()时,UPD 得到同样的错误结果

 document.addEventListener("DOMContentLoaded", function () { var div = document.getElementById("Content"); var res = document.getElementById("Result"); res.innerHTML = div.offsetHeight; // incorrect - returns 252 while the real height is 360 (Firefox, Chrome) });
 div { width: 400px; } img { float: left; margin: 0.5em; }
 <div id="Content"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

To accurately determine the height of the div and the image.准确确定div和图片的高度。 This is because the image will likely finish loading last - if the height of the container is checked before the image is loaded, it will return height without taking the image height into consideration.这是因为图像可能会最后完成加载 - 如果在加载图像之前检查容器的高度,它将返回高度而不考虑图像高度。

A listener should be added to the image so it checks the height once the image loads.应将侦听器添加到图像中,以便在图像加载后检查高度。

img.addEventListener('load', onLoad);

Because the styling is simple, offsetHeight and clientHeight should work but to include the entire element (with border and margin) use scrollHeight as described by Element.scrollHeight on MDN web docs因为样式很简单, offsetHeightclientHeight应该可以工作,但要包含整个元素(带边框和边距),请使用scrollHeight ,如MDN 网络文档上Element.scrollHeight所述

The resulting code:结果代码:

<div id="Content">
    <img id="Image" src="https://picsum.photos/id/82/200/150" />
    ...
</div>
<br/>
<span id="Result"></span>
<script>
    var img = document.getElementById("Image");

    function onLoad() {
        var div = document.getElementById("Content");
        var res = document.getElementById("Result");

        res.innerHTML = div.scrollHeight;
    }

    img.addEventListener('load', onLoad);
</script>

The whole example is in a CodeSnadbox here:整个示例在此处的 CodeSnadbox 中:

编辑计算 div 高度 - 已知宽度 - JS

我不确定我是否完全理解您的问题,但您可以使用 javascript 来计算 div 的高度。

var height = document.getElementsByTagName('div').offsetHeight;

You have to use window.onload instead.您必须改用window.onload

The load event is fired when the whole page has loaded, i ncluding all dependent resources such as stylesheets and images . load 事件在整个页面加载后触发,包括所有依赖资源,如样式表和图像 This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded , without waiting for resources to finish loading.这与 DOMContentLoaded 形成对比,DOMContentLoaded在页面 DOM 加载后立即触发,无需等待资源完成加载。 ref 参考

In your case you need to wait for the image and not only the DOM.在您的情况下,您需要等待图像而不仅仅是 DOM。

 window.onload = function() { var div = document.getElementById("Content"); var res = document.getElementById("Result"); res.innerHTML = div.offsetHeight; };
 div { width: 400px; } img { float: left; margin: 0.5em; }
 <div id="Content"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

I know that you are asking to resize the div once the image loads to make the div taller, but just as a side comment, do you know/have you tried background-size: contains?我知道您要求在图像加载后调整 div 的大小以使 div 更高,但作为旁注,您是否知道/是否尝试过 background-size: contains?

As specified by MDN:按照 MDN 的规定:

The contain value specifies that, regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.包含值指定,无论包含框的大小如何,都应缩放背景图像,使每一边尽可能大,同时不超过容器相应边的长度。

The cover value:封面价值:

The cover value specifies that the background image should be sized so that it is as small as possible while ensuring that both dimensions are greater than or equal to the corresponding size of the container. cover 值指定背景图像的大小应尽可能小,同时确保两个维度都大于或等于容器的相应大小。 Try resizing the example below to see this in action.尝试调整以下示例的大小以查看其实际效果。

When combined with background-position I think it can be really useful当与背景位置结合时,我认为它真的很有用

if u want to use jquery then this is the way如果你想使用 jquery 那么这就是方法

 $(document).ready(function(){ $("#Result").html($("#Content").height()); })
 div { width: 400px; } img { float: left; margin: 0.5em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="Content"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

Not dynamically, since you have the width set it wouldn't be hard to calculate it because it won't change in different screens.不是动态的,因为你设置了宽度,所以计算它并不难,因为它不会在不同的屏幕上改变。 But the only way is doing it MANUALLY USING DEV TOOLS.但唯一的方法是使用开发工具手动完成。

If the image and the font will change, you can have a javascript script that after onlaod it will see what height does the div has.如果图像和字体会改变,你可以有一个 javascript 脚本,在 onlaod 之后它会看到 div 的高度。 (if you need this comment below) (如果您需要下面的评论)

In js you can get the height of any element.在 js 中,您可以获取任何元素的高度。 width is not at all needed to calculate height.计算高度根本不需要宽度。

since div is some generic tag, add some id to make specific to make sure the right tag is targeted to calculate height由于 div 是一些通用标签,添加一些 id 以确保正确的标签用于计算高度

 var element_height = document.getElementById("ElToCalHeight").offsetHeight; alert('Element height ' + element_height);
 <div id="ElToCalHeight"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labo... </div>

You can use .scrollHeight property.您可以使用.scrollHeight属性。

 document.addEventListener("DOMContentLoaded", function() { var div = document.getElementById("Content"); var res = document.getElementById("Result"); res.innerHTML = div.scrollHeight; });
 div { width: 400px; } img { float: left; margin: 0.5em; }
 <div id="Content"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

DOMContentLoaded event is fired when the browser fully loads the HTML and the DOM tree is built, but external resources like pictures and stylesheets are not yet loaded.当浏览器完全加载 HTML 并构建 DOM 树时,会触发DOMContentLoaded事件,但尚未加载图片和样式表等外部资源。 While window.onload event is fired when the whole page is loaded including styles, images, and other resources.window.onload事件在整个页面加载时触发,包括样式、图像和其他资源。

And you got the height as 252 rather than 360 because the height of the div without your image is 252. For reference, you can run the below snippet.你得到的高度是252 而不是 360,因为没有图像的 div 的高度是 252。作为参考,你可以运行下面的代码片段。

This code snippet corresponds to div without image and using window.onload (So height is 252)此代码段对应于没有图像并使用 window.onload 的 div(因此高度为 252)

 window.onload = function() { var div = document.getElementById("Content"); var res = document.getElementById("Result"); res.innerHTML = div.offsetHeight; };
 div { width: 400px; } /** img { float: left; margin: 0.5em; }**/
 <div id="Content"> <!-- Image tag is not present --> <!--<img src="https://picsum.photos/id/82/200/150" />--> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

This following code snippet corresponds to div with image and using window.onload and now the height will come up to be 360 as expected.下面的代码片段对应于带有图像和使用 window.onload 的 div,现在高度将达到预期的 360。

 window.onload = function() { var div = document.getElementById("Content"); var res = document.getElementById("Result"); res.innerHTML = div.offsetHeight; };
 div { width: 400px; } img { float: left; margin: 0.5em; }
 <div id="Content"> <img src="https://picsum.photos/id/82/200/150" /> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Orci phasellus egestas tellus rutrum. Tempor nec feugiat nisl pretium fusce. Cras pulvinar mattis nunc sed blandit libero volutpat sed cras. Purus sit amet luctus venenatis lectus magna fringilla urna. Ut tristique et egestas quis. Mauris cursus mattis molestie a iaculis at erat pellentesque adipiscing. Iaculis eu non diam phasellus vestibulum lorem sed risus ultricies. Semper quis lectus nulla at. Augue interdum velit euismod in. Amet aliquam id diam maecenas ultricies mi eget. Scelerisque viverra mauris in aliquam sem fringilla ut morbi. Et egestas quis ipsum suspendisse. Et malesuada fames ac turpis. Fermentum iaculis eu non diam phasellus vestibulum lorem sed. </div> <br/> <span id="Result"></span>

100% Working! 100% 工作! use Window.onload function instead of DOMContentLoaded使用Window.onload函数代替DOMContentLoaded

  <script>
      window.onload = function() {
      var div = document.getElementById("Content");
      var res = document.getElementById("Result");

      res.innerHTML = div.offsetHeight; 
    };
    </script>

Will give your Result!会给你的结果!

You should check the method element.getBoundingClientRect() after loading.您应该在加载后检查element.getBoundingClientRect()方法。 It will return a set of properties such as width and height.它将返回一组属性,例如宽度和高度。

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

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