2 回答

TA貢獻1860條經驗 獲得超9個贊
您的方法的問題在于代碼是在加載頁面之前執行的。如這里所示,您可以使用vanilla javascript執行類似操作,直到頁面加載。
let field = document.getElementById('field');
let ball = document.getElementById('ball');
window.onload = () => {
console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);
};

TA貢獻1827條經驗 獲得超9個贊
您只應在圖像加載后檢查圖像的大小??梢允褂?image 元素的屬性來查看它是否已加載,否則會將處理程序附加到 load 事件。loaded
let ball = document.getElementById('ball');
const checkImgSize = el => {
console.log(`natural height and width: ${el.naturalHeight} - ${el.naturalWidth}`);
console.log(`client height and width: ${el.clientHeight} - ${el.clientWidth}`);
};
if( ball.loaded )
checkImgSize(ball);
else
ball.addEventListener('load', function(){ checkImgSize(this) }, { once: true });
添加回答
舉報