当视口小于特定大小时,如何告诉srcset属性加载NO图像 [英] How do I tell srcset attribute to load NO images when viewport smaller than certain size

查看:238
本文介绍了当视口小于特定大小时,如何告诉srcset属性加载NO图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解如何保持 srcset 加载屏幕上的任何图片< 768px

I'm having trouble understanding how to keep srcset from loading any images on screens < 768px.

我已经尝试过以下代码,但尺寸属性似乎没有做到你想象的那样。
在所有屏幕尺寸下加载 1024.jpg

I've tried the code below but the sizes attribute doesn't seem to do what you may think. Below loads 1024.jpg on all screen sizes:

<img 
  src="default.jpg"
  srcset="img/1024.jpg 1024w" 
  sizes="(min-width: 768px) 768px, 100vw"
/>

或图片元素,如果它会尊重空srcset 但它只暗示浏览器应该加载哪个图像。

Or the picture element, if it would honor an empty srcset but it only "hints" to which image a browser should load.

推荐答案

另一个答案并不令人满意。通常使用 srcset ,您可以让浏览器选择候选图像。虽然您可以假设在某些设备上拍摄了哪些图像。你没有任何控制权。可以采用 srcset 中的每个图像。

The other answer isn't really satisfying. In general with srcset you give the browser the choice to select an image candidate. While you can assume which image is taken on certain devices. You don't have any control. Each image in srcset can be taken.

因此,如果您想控制,使用或不使用的图像,你需要使用图片元素。

So if you want to control, what is used or not used, you need to use the picture element.

以下是3个例子。如果视口为768像素或更宽,则会下载img / 1024.jpg图像,否则会选择数据uri或损坏的 img

Here are 3 examples. If the viewport is 768px or wider the 'img/1024.jpg' image is downloaded, otherwise a data uri or a broken img is selected.

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="img/1024.jpg" media="(min-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" alt="Image">
</picture>

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" media="(max-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img src="img/1024.jpg" alt="Image">
</picture>

<!-- you can also write (but this makes it invalid) -->

<picture>
  <!--[if IE 9]><video style="display: none;"><![endif]-->
  <source srcset="img/1024.jpg" media="(min-width: 768px)">
  <!--[if IE 9]></video><![endif]-->
  <img alt="Image">
</picture>

虽然第一个和第二个代码示例绝对有效。目前有一些讨论允许通过简单地省略 srcset (参见代码示例2)。请在此处查看此讨论: https://github.com/ResponsiveImagesCG/picture-element/issues/ 243

Although the first and the second code example are absolutely valid. There is currently some discussion to allow this by simply omitting the srcset (see code example 2). See this discussion here: https://github.com/ResponsiveImagesCG/picture-element/issues/243

这篇关于当视口小于特定大小时,如何告诉srcset属性加载NO图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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