javascript - img.width 和 img.height 随机返回 0

标签 javascript html

感谢现有的线程,我能够想出以下代码:

var img = new Image();
img.src = imgSrc;
if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){
    document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width;
} else {
    document.getElementById('size' + lineCount).innerHTML = img.naturalHeight + 'x' + img.naturalWidth;
}

你基本上可以忽略 lineCount 部分。它只是应该在 html 列表中显示不同图像的大小。然而,有时宽度或高度返回为 0。对我来说,它似乎是随机的,因为如果我再次运行脚本,将加载正确的数量,而其他地方则为 0。如果我尝试通过 Microsoft Edge 函数调试代码一切正常,不会有任何 0。

这是我的 Microsoft Edge 引起的问题还是我错过了什么?

最佳答案

您需要等待图像完成加载,然后获取其大小。像这样尝试一下:

var img = new Image();
img.onload = function () {
    if(imgSrc.substring(imgSrcLength-4, imgSrcLength) == '.ico'){
        document.getElementById('size' + lineCount).innerHTML = img.height + 'x' + img.width;
    } else {
        document.getElementById('size' + lineCount).innerHTML = img.naturalHeight + 'x' + img.naturalWidth;
    }
};
img.src = imgSrc;

关于javascript - img.width 和 img.height 随机返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876857/

相关文章:

html - 响应式 CSS 表格布局使一个单元格表现得像一行

javascript - 基础导航顶部栏不适用于 thymeleaf

javascript - JavaScript 中的目标元素

javascript - 路由到同一页面上的多个组件

javascript - 添加到 DOM 后立即在 Jquery 中调整图像大小?

javascript - 在响应表中,第二列值与第一列值重叠

html - CSS悬停 - 它可以影响具有相同类名的多个div吗

javascript - 在执行基于 node-webkit 的应用程序时如何禁用远程脚本和样式表的缓存?

javascript - 下拉 window.onclick javascript 仅适用于一个菜单

php - 获取迭代的 ul 内容的唯一 id