【问题标题】:Can't get the real size of the image in HTML with JS [duplicate]无法使用 JS 在 HTML 中获取图像的实际大小 [重复]
【发布时间】: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


【解决方案1】:

您的方法的问题在于代码是在页面加载之前执行的。正如here 中所见,您可以使用香草 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}`);  
};

【讨论】:

    【解决方案2】:

    您应该只在加载后检查图像的大小。您可以使用图像元素的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 });
    

    【讨论】:

    • 请不要重复回答。相反,如果您有新内容要添加,请在副本中添加答案。
    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多