我认为更新这些答案很有用,因为投票最多的回复之一建议使用 clientWidth 和 clientHeight,我认为它们现在已经过时了。
我用 HTML5 做了一些实验,看看实际返回了哪些值。
首先,我使用了一个名为 Dash 的程序来大致了解图像 API。
它指出 height 和 width 是图像的渲染高度/宽度,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