javascript - 获取图像的宽度和高度
问题描述
所以我有一个元素,我想获取图像的高度和宽度属性,但是这是我的 css:
let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''));
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''));
console.log(`width`,w);
console.log(`height`,h);
img#image{
z-index: 0;
display: block;
top: 0px;
margin-left: auto;
margin-right: auto;
max-height: 100%;
max-width: 100%;
position: absolute;
align-self: center;
margin: auto;
left: 0;
right: 0;
}
<img src="src.jpg" id="image">
如您所见,我没有设置高度和宽度属性,因为我不希望图像具有固定的宽度和高度,所以有人介绍我使用:
window.getComputedStyle(document.getElementById('image')).getPropertyValue('height')
所以我做到了,但从我的经验来看并不准确:
JS:
let h = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('height').replace('px',''))
let w = Number(window.getComputedStyle(document.getElementById('image')).getPropertyValue('width').replace('px',''))
console.log(`width`,w)
console.log(`height`,h)
这是它记录的结果的屏幕截图: https ://media.discordapp.net/attachments/244238416248569857/812200556403490847/Screenshot_1540.png?width=1067&height=600
这是元素实际宽度和高度的屏幕截图: https ://media.discordapp.net/attachments/244238416248569857/812200556000313354/Screenshot_1541.png?width=1067&height=600
如您所见,图像为 670 x 514,但其高度为 459,任何人都可以帮我解决这个问题吗?
解决方案
棘手的世界
问题是您的图像需要先加载。
不过,这是一个非常有趣的问题。
在这里,在下面的代码中,我们正在检查图像是否加载,如果是,我们直接获取宽度和高度没有任何问题。
但是如果图像还没有加载,我们设置一个事件监听器来跟踪它。当它被加载时,事件监听器中的函数将被调用,就是这样。现在您可以访问有关图像的所有信息。
const img = document.getElementById("img");
if(img.complete) {
console.log(img.width, img.height);
} else {
img.addEventListener('load', function() {
const imageWidthRendered = this.width;
const imageHeightRendered = this.height;
console.log(imageWidthRendered, imageHeightRendered)
});
}
<img id="img" src="https://source.unsplash.com/random/100x200">
推荐阅读
- html - HTML 只是一个连续的图像
- c# - 没有为此 DbContext 配置数据库提供程序。尝试更新数据库时出错
- javascript - 如何让一个按钮单击 React 中不同组件的另一个按钮
- python - Pandas - 如何对格式化为字符串的周数和年份数进行排序?
- excel - 编译错误 - 更新枢轴时预期的数组
- c++ - 我需要知道编译器如何与 cpp 中的析构函数一起工作
- sql - 更高效的多层sql语句编写方式
- javascript - 在大画布 JavaScript 游戏上移动播放器
- python - 不知道为什么我的 Kivy 下拉列表没有显示
- asp.net - 为什么 Delivery Preview API 显示也发布内容?