且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript appendChild onload事件

更新时间:2023-12-04 23:25:04

不幸的是,看来您必须交还控件。到浏览器(像您一样使用 setTimeout())之前,可以观察到最终尺寸;幸运的是,超时时间可能非常短。

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,建议仅设置 .src

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.

演示