简体   繁体   English

使用图片、源和 srcset 时如何检查加载了哪个 src? (img.src 为空)

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

I'm using the picture element with source 's to choose which image to load.我正在使用带有sourcepicture元素来选择要加载的图像。 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!虽然我可以添加一个load侦听器,但我无法确定加载了哪个图像,因为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>

How do I determine which image was loaded?如何确定加载了哪个图像?

In modern browsers that implement this, there appears to be a new property: currentSrc .在实现此功能的现代浏览器中,似乎有一个新属性: currentSrc In the image.onload, you can check for this.在 image.onload 中,您可以检查这一点。 In older browsers, it will use src .在较旧的浏览器中,它将使用src

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM