Jquery 查找图像高度不起作用
我正在尝试使用 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>
I'm trying to use jQuery to find the image height of the first "grand children" of a container, then set the container to that height. But, I can't seem to pull the image height attribute - getting the src works. Any ideas? Is it just trying to pull the heights via CSS? How do i get the "real heights" I can't input the width and height in img tag - so that's not an option ;(
$(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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 API 文档:
因此,不要在
$(document).ready();
中执行脚本,而是使用$(window).load();
或者更好,$(image ).load();
。例如:From the API docs:
So instead of executing your script in
$(document).ready();
use$(window).load();
or better yet,$(image).load();
. For example:你应该等到你的图像被加载 - 类似的事情
you should wait until your image is loaded - something along the line of
您无法获取图像尺寸的原因是它们还没有任何尺寸。该代码在页面加载之后但图像加载之前运行。
加载页面中的所有元素后,运行需要图像大小的代码部分:
The reason that you can't get the size of the images is that they don't have any size yet. The code runs after the page has loaded but before the images has loaded.
Run the part of the code that needs the image size after all elements in the page are loaded: