本文介绍了计算给定已知宽度的div高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有一个div,其中包含图片和一些文本(图像的大小可变,文本的长度可变).给定精确的宽度,是否有任何方法可以计算适合所有div内容的高度?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).Is there any way to calculate the height required to fit all the div content, given that the exact width is predefined?使用 $(document).ready()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>推荐答案您必须改用 window.onload .在您的情况下,您不仅需要等待图像,而且还需要等待DOM.In your case you need to wait for the image and not only the 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> 这篇关于计算给定已知宽度的div高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 15:51