如何使用JavaScript获取图像的宽度和高度

How to get the width and height of my image with JavaScript?

本文关键字:高度 图像 何使用 JavaScript 获取      更新时间:2023-09-26

我正试图通过使用以下代码来获取图像的宽度和高度,但我收到的都是未定义的。

有人能向我解释一下这是怎么回事吗?

<script>
var img = new Image();
img = document.getElementById("top");
alert(this.width + 'x' + this.height);
</script>
<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg"/>
        </div>
    </div>
</body> 

首先,如果要从文档中获取图像,则不需要调用new Image

do需要等待,直到img元素存在,并且直到img加载。

如果您使用脚本添加图像,并在设置src:之前挂接load事件,这是最简单的

<body>
    <div id="ad">
        <div id="banner"></div>
    </div>
<script>
var img = document.createElement('img')
img.className = "top";
img.id = "top";
img.onload = function() {
  alert(this.width + 'x' + this.height);
};
img.src="frame_2.jpg";
document.getElementById("banner").appendChild(img);
</script>
</body>

可以使用HTML中的图像进行操作,不过,您只需要考虑到在钩住事件之前图像可能已经加载的可能性:

<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg"/>
        </div>
    </div>
<script>
var img = document.getElementById("top");
img.onload = loaded;
if (img.complete) {
    loaded();
}
function loaded() {
  if (img) {
      alert(img.width + 'x' + img.height);
      img.onload = null;
      img = null; // Just as a marker in case of repeated calls
  }
};
</script>
</body>
在这种情况下,

this很可能指向Window。请尝试使用img.widthimg.height

试试这个:

img = document.getElementById("top");
img.onload = function() {
  alert(img.width + 'x' + img.height);
};
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="http://fpoimg.com/300x300"/>
        </div>
    </div>

如果以后用DOM上查询的元素重新分配该变量,则不需要创建Image的实例。。。

顺便说一句,您需要等待Dom Ready或Window Loaded(指示用于媒体对象)事件。。。

document.addEventListener('DOMContentLoaded', function() {
  var img = document.querySelector('.my-image');
  document.querySelector('#result').innerHTML = img.width + ' x ' + img.height;
});
<h1 id="result"></h1>
<img src="http://www.keenthemes.com/preview/conquer/assets/plugins/jcrop/demos/demo_files/image1.jpg" class="my-image" />

我正试图通过使用以下代码来获得我的图像宽度和高度,但我收到的都是未定义的。

这是因为您试图在创建图像之前在DOM中选择图像。

如果你想获得图像尺寸,你可以做很多方法。如果你想简单地检查它们,你可以执行内联

<body>
    <div id="ad">
        <div id="banner">
            <img class="top" id="top" src="frame_2.jpg" onload="console.log(this.width + ' x ' + this.height + ' px');"/>
        </div>
    </div>
</body> 

您可以通过clientWidthclientHeight获得此功能。

var width = img.clientWidth;
var height = img.clientHeight;

请参阅clientWidth和clientHeight

CSS和其他样式-可能会改变问题的结果。

使用属性:naturalWidthnaturalHeight

它们提供正确的图像大小。

为什么不尝试简单的jQuery?

var imageWidth = $('#top').width();
var imageHeight = $('#top').height();
alert(imageWidth + 'x' + imageHeight);