Javascript appendChild onload event

不羁岁月 提交于 2019-12-02 03:37:53

Unfortunately, it seems that you have to hand the controls back to the browser (using setTimeout() as you did) before the final dimensions can be observed; luckily, the timeout can be very short.

container.appendChild(img);
setTimeout(function() {
    console.log(img.width);
}, 0);

In other words, the repaint (and layout update) is done as soon as your function returns and before the setTimeout fires.

Btw, it's advisable to only set the .src property after you've attached the load handler; I've had to debug my code a few times before I realised that cached images may trigger the load handler immediately upon changing .src.

Demo

var img = new Image();
var container = document.getElementsByTagName("div")[0];
container.appendChild(img);

img.onload = function() {
  alert('Width = ' + img.width);
}

img.src = "http://globe-views.com/dcim/dreams/image/image-03.jpg";
div {
    width: 200px;
}

img {
    display: block;
    width: 100%;
    height: 100%;
}
<div></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!