Javascript appendChild onload event

前端 未结 2 1756
栀梦
栀梦 2021-01-21 08:54

I\'m appending the dynamically created image element to document.

var img = new Image();
img.src = \'test.jpg\',
img.onload = function() {

    var addedImg = co         


        
相关标签:
2条回答
  • 2021-01-21 09:26

    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>

    0 讨论(0)
  • 2021-01-21 09:38

    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

    0 讨论(0)
提交回复
热议问题