【发布时间】:2020-05-21 02:48:19
【问题描述】:
我有一个从外部资源获得的球图像,我需要获取图像的大小(高度和宽度)以进行进一步计算,但我尝试显示的结果为 0(但实际上是 40 像素)
这是整个代码:
<!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>
【问题讨论】:
-
如果您尝试在加载之前获取图像的尺寸,我想它们会为零。尝试在加载事件发生后执行您的逻辑。
标签: javascript html