admin管理员组

文章数量:1208155

When you're using srcset like this:

<img src="example-src.jpg" srcset="example-1x.jpg 1x, example-2x.jpg 2x" />

Or using a picture tag like this:

<picture>
   <source media="(min-width: 64em)" src="high-res.jpg">
   <source media="(min-width: 37.5em)" src="med-res.jpg">
   <source src="low-res.jpg">
   <img src="fallback.jpg" />
</picture>

Is it possible to find out what URL the browser decided to use? Checking the src attribute of the <img> tag itself doesn't actually tell you which image was loaded.

(Sorry if this is a duplicate. I can't find the solution to this anywhere.)

When you're using srcset like this:

<img src="example-src.jpg" srcset="example-1x.jpg 1x, example-2x.jpg 2x" />

Or using a picture tag like this:

<picture>
   <source media="(min-width: 64em)" src="high-res.jpg">
   <source media="(min-width: 37.5em)" src="med-res.jpg">
   <source src="low-res.jpg">
   <img src="fallback.jpg" />
</picture>

Is it possible to find out what URL the browser decided to use? Checking the src attribute of the <img> tag itself doesn't actually tell you which image was loaded.

(Sorry if this is a duplicate. I can't find the solution to this anywhere.)

Share Improve this question asked Feb 23, 2016 at 19:44 Tyler V.Tyler V. 2,56124 silver badges45 bronze badges 1
  • @Teemu This did not work for me. – Tyler V. Commented Feb 23, 2016 at 20:09
Add a comment  | 

3 Answers 3

Reset to default 23

You can use currentSrc in at least some browsers, (though I don't know which.)

document.getElementById('myImage').currentSrc;

Or...

jQuery('#myImage').prop('currentSrc');

This isn't possible at the moment, as far as I'm aware. I put a use case/feature request ("3.10 Managing source swapping between breakpoints") in for something almost identical to this to the RICG. So I hope it's still in the pipeline. But unfortunately it's not something that can be accessed at the moment.

If you just want to now wich source is used:

  1. Use inspect (ctrl+shift+i).
  2. Go to the Network tab, be sure cache is disabeled and reload the page (F5 or ctrl + R).
  3. Select Img to shorten the list.

In the list you will find which image is loaded. If you change the screensize and reload, you will see the change in the results.

本文标签: htmlDetect used srcset or picture tag source with JavaScriptStack Overflow