我正在尝试使用 jQuery 查找容器的第一个“孙子”的图像高度,然后将容器设置为该高度。但是,我似乎无法提取图像高度属性 - 让 src 起作用。有任何想法吗?它只是想通过 CSS 来拉高吗?我如何获得“真实高度”我无法在 img 标签中输入宽度和高度 - 所以这不是一个选项;(
$(document).ready(function() {
var imageContainer = '#image-container';
var imageSrc = $(imageContainer).children(':first').children(':first').attr('src'); // control test
var imageHeight = $(imageContainer).children(':first').children(':first').height(); // have also tried attr('height')
alert(imageSrc + ' ' + imageHeight);
});
<div id="image-gallery">
<div id="image-container">
<div class="slide">
<img src="test1.jpg" alt="test1" />
<p>
<strong>This is a test 1</strong>
</p>
</div>
<div class="slide">
<img src="test2.jpg" alt="test2" />
<p>
<strong>This is a test 2</strong>
</p>
</div>
</div>
</div>
最佳答案
来自API docs :
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
因此,不要在 $(document).ready();
中执行脚本,而是使用 $(window).load();
或更好的方法, $(图像).load();
。例如:
$(document).ready(function() {
var imageContainer = '#image-container';
$(imageContainer).children(':first').children(':first').load(function() {
var imageSrc = $(this).attr('src'); // control test
var imageHeight = $(this).height(); // have also tried attr('height')
alert(imageSrc + ' ' + imageHeight);
});
});
关于javascript - Jquery 查找图像高度不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2150816/