2013-07-08 48 views
1

我需要獲取從API加載的圖像的寬度和高度,不會將css應用於圖像。圖像可能有不同的大小取決於在API中加載的內容在使用jquery或vanilla js的時刻,我的寬度和高度總是爲0?如何檢索延期圖像的寬度和高度?

我的代碼有什麼問題?我應該在創建img標籤時動態設置寬度和高度嗎?怎麼做?

this.getItemSize = function() { 
     var elm = $('#' + scope.elmItem); 
     var pos = elm.offset(); 

     /* also with this vanila js does not work 
     var image = document.getElementById(scope.elmItem); 
     console.log(image); 
     var width = image.offsetWidth; 
     var height = image.offsetHeight; 
     */ 

     scope.itemTop = pos.top; 
     scope.itemLeft = pos.left; 
     scope.itemWidth = elm.width(); 
     scope.itemHeight = elm.height(); 
     console.log(scope.itemTop + " " + scope.itemLeft + " " + scope.itemWidth + " " + scope.itemHeight); 
    }; 



      $.get(this.url, function(image) { 
       // add img to the dom 
       var img = $('<img id="item">'); 
       img.attr('src', scope.url); 
       img.appendTo('#' + scope.elm); 

       scope.getItemSize(); 
      }); 
+0

亞歷克斯感謝您的編輯:-) – GibboK

回答

0

你需要調用getItemSize圖像加載後,您可以使用.load()事件處理程序來做到這一點

$.get(this.url, function(image) { 
    // add img to the dom 
    var img = $('<img id="item">'); 
    img.load(function(){ 
     scope.getItemSize(); 
    }) 
    img.attr('src', scope.url); 
    img.appendTo('#' + scope.elm); 
+0

感謝它的工作原理,只是爲了澄清加載一個jQuery的方法? – GibboK

+0

@GibboK是的,它是由'img'觸發的事件,jQuery使用'load'方法向元素 –

+0

註冊加載事件回調非常感謝解釋! – GibboK