gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 14:03:02 24 4
gpt4 key购买 nike

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

如何确定加载了哪张图片?

最佳答案

在实现此功能的现代浏览器中,似乎有一个新属性: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 );
}

关于javascript - 使用图片、源和srcset时如何检查加载了哪个src? (img.src 为空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com