是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?


当前回答

我认为,使用clientWidth和clientHeight已经过时了。

我用HTML5做了一些实验,看看哪些值实际上会被返回。

首先,我使用了一个名为Dash的程序来获得图像API的概述。

它声明了高度和宽度是图像的渲染高度/宽度,而naturalHeight和naturalWidth是图像的固有高度/宽度(仅适用于HTML5)。

我使用了一个高300,宽400的文件中一个美丽的蝴蝶的图像。下面是JavaScript代码:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

然后我使用这个HTML,内联CSS的高度和宽度。

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

结果:

/* Image element */ height == 300         width == 400
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() == 120       width() == 150

/* Actual rendered size */    120                  150

然后我将HTML更改为以下内容:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

也就是说,使用高度和宽度属性而不是内联样式。

结果:

/* Image element */ height ==  90         width == 115
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() ==  90       width() == 115

/* Actual rendered size */     90                  115

然后我将HTML更改为以下内容:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

也就是说,同时使用属性和CSS来查看哪个优先级。

结果:

/* Image element */ height ==  90         width == 115
             naturalHeight == 300  naturalWidth == 400
/* jQuery */      height() == 120       width() == 150

/* Actual rendered size */    120                  150

其他回答

这个答案正是我所寻找的(在jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

使用jQuery,你可以这样做:

var imgWidth = $("#imgIDWhatever").width();

从父div中删除浏览器解释设置是很重要的。所以如果你想要真实的图像宽度和高度,你可以使用

$('.right-sidebar').find('img').each(function(){
    $(this).removeAttr("width");
    $(this).removeAttr("height");
    $(this).imageResize();
});

这是我的一个TYPO3项目示例,我需要图像的真实属性来缩放它与正确的关系。

你还可以使用:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

jQuery的答案:

$height = $('#image_id').height();
$width  = $('#image_id').width();