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

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

问题描述

我有2张图片:一个是桌面版本,一个是移动版本.我希望当视口宽度调整到480px以下时,将桌面图像替换为移动图像,就像下面的CSS带有background-image属性一样:

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

但是它不起作用,浏览器一直显示移动图像,并在调整视口大小时对其进行缩放,但是我希望2张图像保持各自的原始大小.

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天全站免登陆