Html srcset和视口宽度
我有两张图片:一张桌面版,一张手机版。 我希望当视口宽度调整到480px以下时,桌面图像将替换为移动图像,就像使用以下CSS with background image属性一样:Html srcset和视口宽度,html,responsive-design,srcset,Html,Responsive Design,Srcset,我有两张图片:一张桌面版,一张手机版。 我希望当视口宽度调整到480px以下时,桌面图像将替换为移动图像,就像使用以下CSS with background image属性一样: .logo { background-image: url(http://placehold.it/400x200&text=desktop); } media screen and (max-width: 480px) { .logo { background-image: url(http:
.logo { background-image: url(http://placehold.it/400x200&text=desktop); }
media screen and (max-width: 480px) {
.logo { background-image: url(http://placehold.it/300x150&text=mobile); }
}
我想我可以通过srcset HTML属性实现这一点:
<img src="http://placehold.it/400x200&text=desktop" alt="" srcset="http://placehold.it/300x150&text=mobile 480w">
但它不起作用,浏览器始终显示移动图像,并在视口调整大小时重新缩放,但我希望这两幅图像保持各自的原始大小
srcset有可能实现这种行为吗?听起来你想做“艺术指导”,也就是说,图像的不同不仅仅是放大图像的缩小版本。如果是这样,您需要使用
picture
元素
<picture>
<source srcset="http://placehold.it/300x150&text=mobile"
media="(max-width: 480px)">
<img src="http://placehold.it/400x200&text=desktop" alt="...">
</picture>
注意:如果使用srcset
,并且较大的候选图像在缓存中,Chrome将始终显示该缓存的候选图像-无论实际视口大小如何
<img src="http://placehold.it/400x200&text=desktop"
srcset="http://placehold.it/400x200&text=desktop 400w,
http://placehold.it/300x150&text=mobile 300w"
sizes="(max-width: 480px) 300px, 400px">