获取图像的高度 [英] Get the Height of an Image
问题描述
这应该很容易,但事实并非如此.我只需要图像的高度:
This should be easy but it's not. I just need the height of an image:
<div id="map">
<img src="myimage.jpg">
</div>
$("#map img").height(); // returns 0
推荐答案
使用.clientHeight
(纯JavaScript):
Use .clientHeight
(pure JavaScript):
https://jsfiddle.net/ryanpcmcquen/v6yz8t3u/
console.log(document.querySelector('img').clientHeight);
<img src="//makelin.us/100/100" />
在此处进行阅读: https://developer. mozilla.org/zh-CN/docs/Web/API/Element/clientHeight
请注意,这将为您提供图像在页面上显示时的高度,它可能会受到CSS的影响.
Note that this will give you the height as the image appears on the page, it could be affected by CSS.
注意:要获取图像的实际高度,请使用.naturalHeight
.
此处很棒的文章: https://davidwalsh.name/get-image-dimensions
Note: To get the actual height of the image, use .naturalHeight
.
Great article here: https://davidwalsh.name/get-image-dimensions
要确保此操作在映像加载后运行,请执行以下操作:
To make sure this runs after the image has loaded, do:
window.addEventListener('load', function () {
console.log(document.querySelector('img').clientHeight);
});
这篇关于获取图像的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!