我目前正在尝试在我的网站上制作更好的响应图像。经过一些研究,我发现了 srcset
和 sizes
属性。
我的目标如下:
- 当屏幕尺寸大于 600 像素或小于 300 像素时,我想提供 250x250 的图片
- 当它介于这两个值之间时,我想提供一个 350x350 的图像
- 另外,我希望在像素比更高的屏幕上显示更高分辨率的图像
这是我想出来的。但它并没有像我想象的那样工作。始终转换小型 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" />
我还有一个问题:
在我的测试中,我发现在调整窗口大小时浏览器不会加载新图像,因此应该提供不同的图像。有可能吗?
最佳答案
好的。经过一些繁琐的研究后,我发现我没有正确理解 sizes
属性。
以下是我如何实现我想要的:
<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" />
关于html - img srcset 和大小无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31599363/