srcset 和视口宽度 [英] srcset and viewport width

查看:25
本文介绍了srcset 和视口宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 张图片:一张桌面版,一张移动版.当视口宽度调整到 480 像素以下时,我希望桌面图像被移动图像替换,就像使用具有 background-image 属性的以下 CSS 一样:

I have 2 images: one desktop version, one mobile version. I would like the desktop image to be replaced by the mobile image when the viewport width resizes below 480px, just as would with the following CSS with background-image property :

.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 属性来实现这一点:

I thought I could achieve this with the srcset HTML attribute :

<img src="http://placehold.it/400x200&amp;text=desktop" alt="" srcset="http://placehold.it/300x150&amp;text=mobile 480w">

但它不起作用,浏览器一直显示移动图像并在视口调整大小时重新缩放它,但我希望这两个图像保持各自的原始大小.

But it does not work, the browser shows the mobile image all the time and rescales it on viewport resize, but I wish the 2 images remains in their respective original size.

是否可以使用 srcset 实现这种行为?

Is it possible to achieve this behavior with srcset?

推荐答案

听起来您想做艺术指导",即图像的不同之处不仅仅是大图像的缩小版本.如果是这样,您需要使用 picture 元素.

It sounds like you want to do "art direction", i.e. the images are different more than just the smaller being scaled down version of the bigger image. If so, you need to use the picture element.

<picture>
 <source srcset="http://placehold.it/300x150&amp;text=mobile"
         media="(max-width: 480px)">
 <img src="http://placehold.it/400x200&amp;text=desktop" alt="...">
</picture>

但是,如果您的小图像实际上是大图像的缩小版本,那么您可以使用 srcset,但是您无法控制选择哪个图像.由浏览器根据屏幕密度、网络条件、用户偏好、浏览器缓存等选择最好的.

However, if your small image is actually a scaled-down version of the bigger image, then you can use srcset, but then you have no control over which image gets chosen. It's up to the browser to pick the best one based on screen density, network conditions, user preference, browser cache, etc.

<img src="http://placehold.it/400x200&amp;text=desktop"
     srcset="http://placehold.it/400x200&amp;text=desktop 400w,
             http://placehold.it/300x150&amp;text=mobile 300w"
     sizes="(max-width: 480px) 300px, 400px">

注意:如果使用 srcset 并且较大的候选图像在缓存中,Chrome 将始终显示此缓存的候选图像 - 无论实际视口大小如何.

Note: If srcset is used and the larger image candidate is in cache, Chrome will always display this cached image candidate - no matter of the actual viewport size.

这篇关于srcset 和视口宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆