最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Apr 25, 2021 at 11:48 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Dec 19, 2015 at 0:50 Don RhummyDon Rhummy 25.8k52 gold badges192 silver badges361 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 29

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 );
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论