15

我正在使用picture带有 's 的元素source来选择要加载的图像。虽然我可以添加一个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>

如何确定加载了哪个图像?

4

1 回答 1

26

在实现这一点的现代浏览器中,似乎有一个新属性: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 );
}
于 2015-12-19T01:02:26.103 回答