如何在javascript中获取图像的高度

How to get the height of an image in javascript

本文关键字:图像 高度 获取 javascript      更新时间:2023-12-01

假设图像的原始高度为200px或低于100px。然后我设置了图像的"最大高度:100px"。我怎样才能得到它显示的高度。我试过$('img').height()。但它只是给我一个0值吗。

使用window.getComputedStyle(Firefox、Opera、Safari):

示例:

<img style="height:100px;max-height:100px;" src="img.gif" id="test">
var img = document.getElementById('test');
var height = window.getComputedStyle(img).height;
console.log(height)

将输出100px

对于IE,您可以使用

var height = img.currentStyle.height;

使用简单的JavaScript:

var img = document.getElementById('imageid'); // use the id of your image
var height = img.clientHeight;

您需要$('img').innerHeight()-获取匹配元素集中第一个元素的当前计算高度,包括填充但不包括边框http://api.jquery.com/innerHeight/

$(document).ready(function() {
$("img").load(function() {
    alert($(this).height()); // for height
    alert($(this).width());  // for width
});
});

确保您已经在该脚本上初始化了jQuery,因为在本例中,您似乎正试图通过"$"命令使用jQuery。

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

将以上代码放在文档的开头。

体内,但图像

<body>
    <img src="img.jpg" id="new-image" />
</body>

上面是HTML,图像具有"新图像"的ID

可以使用jQuery通过在ID 之前添加#来选择ID

例如"#新图像"

$(document).ready(function(){
    // Retrieves computed image height and stores to variable "imgHeight"
    var imgHeight = $('#new-image').height();
    // Shows current computed/displayed height in development console
    console.log(imgHeight);
    // If you don't know how to access the development console
    // You can also use alert (but you should learn to use the console!)
    alert(imgHeight);
}

请确保将以上代码包装在脚本标记中。