twitter-bootstrap 响应图像:img srcset + Bootstrap,错误大小的图像被加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28364118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 22:17:56  来源:igfitidea点击:

Responsive images: img srcset + Bootstrap, wrong size image gets loaded

twitter-bootstrapresponsive-designpicturefillsrcset

提问by Andrew

I'm using Bootstrap with Responsive Images. I want to optimize load times by offering multiple image sizes to browsers. According to this article, a plain approach with srcset like this is good for letting the browser pick the optimal image size:

我正在将 Bootstrap 与响应式图像一起使用。我想通过向浏览器提供多种图像尺寸来优化加载时间。根据这篇文章,像这样使用 srcset 的简单方法有利于让浏览器选择最佳图像大小:

<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">

My problem is that combining this with the Bootstrap img-responsiveclass, a large size picture gets loaded even when only a small one is needed.

我的问题是,将它与 Bootstrap img-responsive类相结合,即使只需要小图片,也会加载大尺寸图片。

Code example here: Bootply. Use Chrome for testing, it has built-in support for srcset support!(Some other browsers would need picturefill.js to recognize it.)

此处的代码示例:Bootply使用 Chrome 进行测试,它内置了对 srcset 的支持!(其他一些浏览器需要 picturefill.js 来识别它。)

If you copy the source of the image (or look in Chrome Developer Tools in the Network tab), you can see that the 750 width version gets loaded, and resized to a small image, even though there are smaller versions that would be optimal to use. (The same thing happens in IE and Firefox if the picturefill JS is loaded to support img srcset.)

如果您复制图像的来源(或查看“网络”选项卡中的 Chrome 开发人员工具),您可以看到 750 宽度版本被加载,并调整为小图像,即使有更小的版本最适合利用。(如果加载了图片填充 JS 以支持 img srcset,则在 IE 和 Firefox 中也会发生同样的事情。)

What am I doing wrong?

我究竟做错了什么?

回答by alexander farkas

You need to use the sizesattribute to tell the browser which width the image will have in your design, otherwise it defaults to 100vw(full viewport).

您需要使用该sizes属性来告诉浏览器图像在您的设计中的宽度,否则默认为100vw(完整视口)。

<img sizes="(max-width: 480px) calc(100vw - 10px), 480px" src="small.jpg" srcset="small.jpg 600w, medium.jpg 1000w, large.jpg 2000w" alt="yah" />

In case you can set the width in CSS, you can also use lazySizesto automatically calculate the sizesfor you.

如果您可以在 CSS 中设置宽度,您也可以使用lazySizessizes为您自动计算。

With lazySizes:

使用lazySizes:

<img data-sizes="auto" class="lazyload" data-srcset="small.jpg 600w, medium.jpg 1000w, large.jpg 2000w" alt="yah" />