When using picture, source and srcset how check which src was loaded? (img.src is empty)

你说的曾经没有我的故事 提交于 2019-12-20 20:42:14

问题


I'm using the picture element with source's to choose which image to load. And while I can add a load listener, I cannot figure out which image was loaded as the img tag's src attribute and property are both empty, even when loaded!

<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>

How do I determine which image was loaded?


回答1:


In modern browsers that implement this, there appears to be a new property: currentSrc. In the image.onload, you can check for this. In older browsers, it will use src.

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

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


来源:https://stackoverflow.com/questions/34366100/when-using-picture-source-and-srcset-how-check-which-src-was-loaded-img-src-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!