You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生JavaScript获取<img>标签中定义的height和width属性值?

获取img标签内定义的height和width属性值

要直接获取<img>标签上显式定义的height和width属性值,不能用img.naturalHeight或img.height——前者返回图片原始像素高度,后者返回元素实际渲染的高度,都不是标签上写的属性值。

解决方案:使用getAttribute()方法

通过元素的getAttribute()方法可以直接读取标签上的属性字符串值,未定义时返回null,可按需转换为0或undefined。

代码示例:

const img = document.getElementById("testImg");
// 获取标签定义的height,未定义则返回0
const definedHeight = parseInt(img.getAttribute("height"), 10) || 0;
// 获取标签定义的width,未定义则返回0
const definedWidth = parseInt(img.getAttribute("width"), 10) || 0;

console.log(definedHeight);
console.log(definedWidth);

示例验证

情况1:标签显式定义属性

<img id="testImg" src="http://test.com/img.png" height="300" width="250">

执行代码后,definedHeight返回300,definedWidth返回250。

情况2:标签未定义属性

<img id="testImg" src="http://test.com/img.png">

执行代码后,definedHeight和definedWidth均返回0;若不需要转换,直接使用img.getAttribute("height")会返回null。

内容的提问来源于stack exchange,提问作者Tommizzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:31:04