Can I use `<img srcset>` or `<picture>` for image size rather than viewport size?

China☆狼群 提交于 2019-12-10 10:31:39

问题


I'm trying to use <img srcset /> to load images based on the size they'll appear on the page, rather than based on the size of the viewport. Perhaps examples will help:

  • On any viewport, when the image is styled with width: 100% inside a 200px-wide <div>, img-200.jpg should load.
  • On any viewport, when the image is styled with width: 100% inside a 400px-wide <div>, img-400.jpg should load.
  • ...etc.

I've done tons of Googling, but as best as I can tell, srcset is only used for changing images based on viewport size, not image size, if that makes sense. Is that correct? Or is there hope for what I'm trying to accomplish?


回答1:


As was mentioned in the comments, this doesn't exist yet.
However, I've been thinking. If you don't mind a little trickery, there's a workaround.
We can use an iframe.

To the contents of an iframe, its width is the viewport. So then we can use the standard srcset tricks.

Let's say our img looks like this

<img src="https://placehold.it/200x100" alt=""
  srcset="https://placehold.it/200x100 200w, https://placehold.it/500x250 500w">

using the 200x100 image at smaller resolutions (200px or less) and the 500x250 one at higher resolutions.
We can then put this in a HTML file with a zero margin around it, because the iframe expects an actual HTML document.

Now to avoid having to load multiple files, we can turn this into a data URL, which will look as follows:

data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w

and all that will make our original HTML page look something like this.
Note that, to show it works, I included two iframes, which are identical in themselves. Only their CSS widths differ.

iframe {width:200px; height:100px}
iframe ~ iframe {width:400px; height:200px}
<iframe src="data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w' alt=''%3E" frameborder="0">?</iframe>
<br><br>
<iframe src="data:text/html;charset=utf-8,%3Cbody style='margin%3A0'%3E%3Cimg src='https%3A//placehold.it/200x100' srcset='https%3A//placehold.it/200x100 200w, https%3A//placehold.it/500x250 500w' alt=''%3E" frameborder="0">?</iframe>


来源:https://stackoverflow.com/questions/47750594/can-i-use-img-srcset-or-picture-for-image-size-rather-than-viewport-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!