【问题标题】:javascript image onload has 0 width and 0 heightjavascript图像加载具有0宽度和0高度
【发布时间】:2014-11-07 19:09:33
【问题描述】:

我正在从文件系统加载图像,然后我想调整图像大小。它在除 IE (11) 之外的所有浏览器中都能正常工作。问题是图片加载了,但是宽高都是0。

我没有选择,所以我在这里发布这个问题。

这是代码

function getAsImage(readFile, chatboxtitle) {
    var reader = new FileReader();
    reader.readAsDataURL(readFile);
    reader.onload = addImg;

}

function addImg(imgsrc) {
    var img = document.createElement('img');
    img.setAttribute("src", imgsrc.target.result);

    console.log(img);

    console.log(img.width + " "+img.height);

    ... a lot of cool stuff happens here but it doesn't work because width is 0

}

好的,所以控制台打印的图像是这样的

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAH0CAYAAAHUIW ... and much more.. >

所以图像就在那里。除 IE 外,所有浏览器都可以正常工作。

我尝试设置一些 IMG 属性,例如样式、宽度,但没有任何效果。

请注意,我不是核心 JavaScript 开发人员。也许我错过了一些东西。没有找到 DOM 元素?

更新

我昨天尝试了下面的答案,它正在工作。但是我今天尝试了该解决方案,但它不再起作用了。试试这个fiddle。 它不适用于 Windows7 上的 IE11,但它适用于 Windows8 上的 IE11。

【问题讨论】:

标签: javascript html


【解决方案1】:

奇怪的 IE 行为。原来你需要使用

设置 src
img.src = src_goes_here

不是通过setAttribute

(function(doc){
    doc.getElementById('file').addEventListener('change', readFile);

    function readFile(ev) {
        var file = this.files[0],
            reader;

        if(file) {
            reader = new FileReader();
            reader.onload = getSize
            reader.readAsDataURL(file);
        }
    }

    function getSize(ev) {
        var img = doc.createElement('IMG');
        img.src = this.result; //wors in IE11
        //img.setAttribute('src', this.result); //doesn't work

        console.log(img.width, img.height);
    }
}(document))

Demo.

UPD: 一些额外的研究表明,当您使用img.setAttribute 设置 src 时,为了让 IE 计算图像大小,您需要将图像实际附加到文档中。例如

document.body.appendChild(img);

Another Demo.

【讨论】:

  • 有趣,我没有注意到图像没有附加到 DOM,我认为如果不附加到 DOM 就无法获得任何东西的尺寸
  • 奇怪的是你可以设置节点的 src 属性。不是通过setAttribute 方法。
  • 我试过了,它有效,但现在不再有效。看看我添加的小提琴
  • 老兄,仍然对我有用。重新加载浏览器什么的。
  • 好的,它在 Windows 8 上的 IE11 中工作,但在 Windows 7 上的 IE11 中不工作
猜你喜欢
  • 2010-11-26
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2014-01-24
  • 2014-09-24
相关资源
最近更新 更多