[英]Getting the width and height of an Image
所以我有一個元素,我想獲得圖像的高度和寬度屬性,但這是我的 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,任何人都可以幫我解決這個問題嗎?
問題是您的圖像需要先加載。
不過,這是一個非常有趣的問題。
在這里,在下面的代碼中,我們正在檢查圖像是否加載,如果是,我們直接獲取寬度和高度沒有任何問題。
但是如果圖像還沒有加載,我們設置一個事件監聽器來跟蹤它。 當它被加載時,事件監聽器中的 function 將被調用,就是這樣。 現在您可以訪問有關圖像的所有信息。
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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.