2015-12-19 36 views
3

我使用picture元素與source來選擇要加載的圖像。雖然我可以添加load聽衆,但我無法弄清楚哪個圖像已加載,因爲img標籤的src屬性和屬性都是空的,即使在加載時也是如此!使用圖片時,source和srcset如何檢查哪個src被加載? (img.src爲空)

<picture> 
     <source srcset="images/test1.png" media="(min-width: 64em)"> 
     <source srcset="images/test2.png" media="(max-width: 63.99em)"> 

     <!-- This will alert an empty string "" --> 
     <img srcset="images/test.png" alt="" onload="alert(this.src);"> 
</picture> 

如何確定裝載了哪個圖像?

回答

9

在實現此目標的現代瀏覽器中,似乎有一個新屬性:currentSrc。在image.onload中,你可以檢查這個。在較舊的瀏覽器中,它將使用src

img.onload = function() 
{ 
    //Old browser 
    if (typeof img.currentSrc === "undefined") console.log(img.src); 

    //Modern browser 
    else console.log(img.currentSrc); 
}