如何在html/javascript中使用dom检索图像的大小

How to retrieve an image's size using dom in html/javascript?

本文关键字:检索 dom 图像 html javascript      更新时间:2023-09-26

我正在尝试使用这种代码在javascript中获取图像的大小:

var image = document.createElement("img");
image.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";

然后我一直在尝试使用 image.widthimage.naturalWidth 来获取图像的宽度,但它检索到 0。

使用上述代码创建元素后。您可以使用

image.height
image.width

之所以得到 0,是因为当您执行语句时,它不会加载。您必须等到加载图像并执行语句。您可以使用document.ready但问题是它在那里可能不是 100% 准确的。

参考:在执行某些操作之前要求jQuery等待所有图像加载的官方方法

您可以使用window.load(使用jquery),但根据上述文章,这是有风险的。

为了获得最佳解决方案,您可以使用 lib https://github.com/desandro/imagesloaded。

您可以使用@Raman的技术,但问题是您必须将事件侦听器附加到每个图像,这可能会变得团块。

如果您使用的是 imagesloaded,则可以监视要加载的图像的容器并相应地执行代码。

杰斯菲德尔:https://jsfiddle.net/52q0juq6/1/

您需要

根据图像的load计算图像尺寸。这是一个小提琴来证明这一点。

image.addEventListener('load', function(){
  console.log(image.width);
  console.log(image.height);
});

这是因为图像尚未加载。

<html>
<img  id="theImage" src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png" />
<button id="Ok" value="Ok" onclick="ShowImageWidth()" />
<script type="text/JavaScript">
 //This runs when the page loads and shows 0
var element = document.getElementById('theImage');
     alert(element.width); 
//This runs AFTER the page has loaded and the button is clicked and shows 100
function ShowImageWidth() {
    var element = document.getElementById('theImage');
     alert(element.width); 
     }
</script>
</html>