【发布时间】:2021-02-20 16:18:38
【问题描述】:
所以我有一个元素,我想获取图像的高度和宽度属性,但是这是我的 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,任何人都可以帮助我解决这个问题吗?
【问题讨论】:
-
你想让图像的高度和宽度响应吗?这样它就可以在屏幕上自动调整。
-
getComputedStyle 遇到了您现在遇到的问题。它返回布局前值(现在称为使用值),而不是布局后值。请查看本文档注释部分的第 3 段。 developer.mozilla.org/en-US/docs/Web/API/Window/… 为什么不尝试其他方法来衡量这些值?
标签: javascript html