简体   繁体   English

img srcset 和尺寸无法正常工作

[英]img srcset and sizes not working as I would expect

I am currently trying to make better responsive images on my site.我目前正在尝试在我的网站上制作更好的响应式图像。 After some research I found the the srcset and sizes attributes.经过一番研究,我发现了srcsetsizes属性。

My goal here is the following:我的目标如下:

  • When the screen size is above 600px or below 300px I want to serve a 250x250 image当屏幕尺寸高于 600 像素或低于 300 像素时,我想提供 250x250 的图像
  • When it is between these two values I want to serve a 350x350 image当它介于这两个值之间时,我想提供 350x350 的图像
  • Also I want higher resolution images for screens which have a higher pixel ratio我还想要具有更高像素比的屏幕的更高分辨率图像

This is what I came up with.这就是我想出的。 But it is not working as I though it would.但它不像我想的那样工作。 The small 250x250 is always being served.始终提供 250x250 的小型广告。

<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?有可能这样做吗?

Ok.好的。 After some tidious research I found out that I did not understand the sizes -attribute correctly.一些tidious研究后,我发现我不明白sizes正确-attribute。

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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM