我有一个来自外部资源的球的图像,我需要获取图像的大小(高度和宽度)以进行进一步的计算,但是我尝试显示的图像为0(但实际上为40px)
这是整个代码:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Ball to center</title>
<style>
#field {
width: 200px;
border: 10px groove black;
background-color: #00FF00;
position: relative;
}
#ball {
position: absolute;
}
</style>
</head>
<body>
<div id="field">
<img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</div>
<script type="text/javascript">
let field = document.getElementById('field');
let ball = document.getElementById('ball');
console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);
console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);
</script>
</body>
</html>
加载后,您仅应检查图像的大小。您可以使用loaded
image元素的属性来查看它是否已经加载,否则可以将处理程序附加到load事件。
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 });
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句