当使用图片,源和srcset如何检查哪个src被加载? (img.src为空) [英] When using picture, source and srcset how check which src was loaded? (img.src is empty)
本文介绍了当使用图片,源和srcset如何检查哪个src被加载? (img.src为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用图片
元素与 source
来选择要加载的图片。虽然我可以添加一个 load
侦听器,但是我找不到哪个图像被加载为 img
标签的<$ c
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?
推荐答案
在实现这一功能的现代浏览器中,似乎有一个新属性: currentSrc
。在image.onload中,你可以检查这个。在较旧的浏览器中,它将使用 src
。
$ b
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 );
}
这篇关于当使用图片,源和srcset如何检查哪个src被加载? (img.src为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文