如何在javascript中获取图像的高度
How to get the height of an image in javascript
假设图像的原始高度为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);
}
请确保将以上代码包装在脚本标记中。
相关文章:
- 如果宽度是百分比,如何设置以px为单位的图像高度
- 根据图像高度添加类
- 尝试使用window.innerHeight和Javascript设置图像高度
- 图像高度只会从一大组图像中检索一次
- 为什么我的图像高度没有改变
- 使图像高度相同并定义共享的总宽度
- 在提交表单之前获取上传图像的图像高度和宽度
- Javascript:在 for 循环中编辑图像高度
- 如何使用 JQuery 获取真实的图像高度
- 根据原始图像高度使用 Photoshop 和 JavaScript 调整条件图像大小
- 基于移动方向的图像高度
- 我如何使用 Jquery 获取图像高度并将其除以 2
- 图像高度与图像宽度成比例,但图像宽度以父项的百分比为单位
- 使用 jQuery 调整图像高度
- 获取图像高度并将图像容器高度更改为自动
- 图像高度始终返回为0
- 获取不在内容中的图像高度
- 调整主图像高度的Nivo滑块
- 如何使用变量更改图像高度
- 获取图像高度属性并将其显示在CSS转换中