img srcset和大小无法正常工作
我目前正在尝试在我的网站上制作更好的响应式图像.经过一番研究,我发现了 srcset
和 sizes
属性.
I am currently trying to make better responsive images on my site. After some research I found the the srcset
and sizes
attributes.
我的目标是:
- 当屏幕尺寸大于600像素或小于300像素时,我要投放250x250的图片
- 当介于这两个值之间时,我要提供350x350的图片
- 我还想为像素比更高的屏幕提供更高分辨率的图像
这是我想出的.但这并没有像我所希望的那样起作用.始终会投放250x250的小型广告.
This is what I came up with. But it is not working as I though it would. The small 250x250 is always being served.
<img src="https://placehold.it/250"
srcset="https://placehold.it/700 700w, https://placehold.it/500 500w, https://placehold.it/350 350w, https://placehold.it/250 250w"
sizes="((max-width: 600px) and (min-width: 300px) and (min-resolution: 2)) 350px, (min-resolution: 2) 250px, ((max-width: 600px) and (min-width: 300px)) 350px, 250px" />
我还有一个问题:
在我的测试中,我发现调整窗口大小时浏览器将不会加载新图像,因此应提供其他图像.可以这样做吗?
And I have one additional question:
In my tests I found out that the browser won't load new images when the window is resized so that a different image should be served. Is it possible to do that?
好.经过一些艰苦的研究,我发现我不正确理解 sizes
属性.
Ok. After some tidious research I found out that I did not understand the sizes
-attribute correctly.
以下是我如何实现自己想要的东西:
The following is how I can achieve what I want:
<img src="https://placehold.it/250"
srcset="https://placehold.it/700 700w, https://placehold.it/500 500w, https://placehold.it/350 350w, https://placehold.it/250 250w"
sizes="(max-width: 600px) calc(100vw - 50px), 250px" />