Html 是否有 srcset 等效于 css 背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26801745/
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-08-29 03:00:50  来源:igfitidea点击:

Is there a srcset equivalent for css background image

htmlcssbackground-imagesrcset

提问by Martin Algesten

imgwith srcsetattribute looks like a great way of doing responsive images. Is there an equivalent syntax that works in css background-imageproperty?

imgwithsrcset属性看起来是一种制作响应式图像的好方法。是否有适用于 cssbackground-image属性的等效语法?

HTML

HTML

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

CSS

CSS

.mycontainer {
    background: url(?something goes here?);
}

采纳答案by Yoav Weiss

image-setis the equivalent CSS feature. We should add equivalent srcset functionality (defining resources according to their dimensions) to the spec.

image-set是等效的 CSS 功能。我们应该在规范中添加等效的 srcset 功能(根据资源的维度定义资源)。

Currently it's only implemented in Safari, Chrome and Opera with the -webkit-prefix, and it only supports the xdescriptors.

目前它只在 Safari、Chrome 和 Opera 中使用-webkit-前缀实现,并且只支持x描述符。

回答by SRing

Pretty sure that:

很确定:

background: -webkit-image-set( url('path/to/image') 1x, url('path/to/high-res-image') 2x );

works the same way. The browser will examine the images, see which fits best and will use that one.

工作方式相同。浏览器将检查图像,看看哪个最适合并使用那个。

回答by Parks

Another approach, which is quite frankly more robust, would be to adapt the characteristics and options of background images to an image with the srcset attribute.

坦率地说,另一种更健壮的方法是使背景图像的特征和选项适应具有 srcset 属性的图像。

To do this, set the image to be width: 100%; height: 100%; and object-fit: cover or contain.

为此,将图像设置为 width: 100%; 高度:100%;和对象适合:覆盖或包含。

Here is an example:

下面是一个例子:

.pseudo-background-img-container {
  position: relative;
  width:400px;
  height: 200px;
}
.pseudo-background-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="pseudo-background-img-container">

<img class="pseudo-background-img" src="https://cdn3.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep.jpg" srcset="https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep.jpg 640w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-280x175.jpg 280w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-432x270.jpg 432w, https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2016/12/Keep-216x135.jpg 216w" sizes="(max-width: 640px) 100vw, 640px">

</div>

This may not be the best approach for everyone but I imagine it will get most the desired results without any javascript workaround.

这可能不是每个人的最佳方法,但我想它会在没有任何 javascript 解决方法的情况下获得最理想的结果。

回答by Weston

For a polyfill, you can use an img with srcset as a mechanism for downloading the correct image size, then use JS to hide it and set the background-image of a parent element.

对于 polyfill,您可以使用带有 srcset 的 img 作为下载正确图像大小的机制,然后使用 JS 隐藏它并设置父元素的背景图像。

Here's a fiddle: http://jsbin.com/garetikubu/edit?html,output

这是一个小提琴:http: //jsbin.com/garetikubu/edit?html,output

The use of onloadand putting the JS as a blocking script in the <head>is important. If you put the script later (say at the end of <body>), you can get a race condition where img.currentSrc hasn't been set yet by the browser. It's best to wait for it to be loaded.

使用onloadJS 并将其作为阻塞脚本放在 中<head>很重要。如果您稍后放置脚本(比如在 的末尾<body>),您可能会遇到浏览器尚未设置 img.currentSrc 的竞争条件。最好等待加载完成。

The example allows you to see the original img being downloaded. You can easily hide it with some CSS.

该示例允许您查看正在下载的原始 img。您可以使用一些 CSS 轻松隐藏它。

回答by gtamborero

You can use media queries for your purpose. It's easy as this:

您可以根据自己的目的使用媒体查询。这很简单:

.mycontainer {    
    background-image:url("img/image-big.jpg"); // big image   
}

@media(max-width: 768px){
   .mycontainer {
        background-image:url("img/image-sm.jpg"); // small image  
    }
}

And I think it works on every browser who support media queries ;)

而且我认为它适用于支持媒体查询的每个浏览器;)

回答by Piotr ?ciga?a

Similar solution using <picture>element: Tutorial here

使用<picture>元素的类似解决方案: 此处的教程

Tutorial's case:

教程案例:

I'm doubtful that if I use the same image for a smaller screen size, the primary subject of my image may become too small in size. I want to display a different image (more focused on the primary subject) in a different screen size, but I still want to display separate assets of the same image based on device-pixel ratio, and I want to customize height and width of the image based on viewport.

我怀疑如果我将相同的图像用于较小的屏幕尺寸,我的图像的主要主题可能会变得太小。我想以不同的屏幕尺寸显示不同的图像(更专注于主要主题),但我仍然想根据设备像素比显示同一图像的不同资产,并且我想自定义图像的高度和宽度基于视口的图像。

Example code:

示例代码:

<picture>

<source media="(max-width: 20em)" srcset="images/small/space-needle.jpg 1x,
images/small/space-needle-2x.jpg 2x, images/small/space-needle-hd.jpg 3x">

<source media="(max-width: 40em)" srcset="images/medium/space-needle.jpg 1x,
images/medium/space-needle-2x.jpg 2x, images/medium/space-needle-hd.jpg 3x">

<img src="space-needle.jpg" alt="Space Needle">

</picture>

回答by jave.web

Based on @Weston's answer, I've built a more general jQuery solution, you can basically just copy&paste the JS and CSS and focus on the HTML part ;)

根据@Weston的回答,我构建了一个更通用的 jQuery 解决方案,您基本上可以复制&粘贴 JS 和 CSS 并专注于 HTML 部分;)

TL;DR - fiddle: https://jsfiddle.net/dpaa7oz6/

TL; DR - 小提琴:https: //jsfiddle.net/dpaa7oz6/

CSS

CSS

...to ensure images will be hardly visible while loading

...以确保图像在加载时几乎不可见

.srcSet{
  position: fixed;
  z-index: 0;
  z-index: -1;
  z-index: -100;
  /* you could probably also add visibility: hidden; */
}

JS / jQuery

JS / jQuery

This script will go through all images that have srcSetclass and bind loadevent that takes currentSrc(or srcif not supported) and puts it as a background-imageCSS to the closest parent with bgFromSrcSetclass.

该脚本将遍历所有具有srcSet类和绑定load事件的图像currentSrcsrc如果不支持),并将其作为background-imageCSS放置到最近的具有bgFromSrcSet类的父级。

That itself would not be enough!So it also puts an interval checker on windowloadevent to test if the load events have been completed, if not, it triggers them. (imgloadevent is very often trigger only on first-time load, on following loads, image source could be retrieved from cache, resulting in img load event NOTbeing fired!)

这本身是不够的!所以它还在windowload事件上放置了一个间隔检查器来测试加载事件是否已经完成,如果没有,它会触发它们。(imgload事件通常只在第一次加载时触发,在后续加载时,可以从缓存中检索图像源,导致 img 加载事件不会被触发!

jQuery(function($){ //ON DOCUMENT READY
  var $window = $(window); //prepare window as jQuery object

  var $srcSets = $('.srcSet'); //get all images with srcSet clas
  $srcSets.each(function(){ //for each .srcSet do...
    var $currImg = $(this); //prepare current srcSet as jQuery object

    $currImg
      .load(function(){ //bind the load event
          var img = $currImg.get(0); //retrieve DOM element from $currImg

          //test currentSrc support, if not supported, use the old src
          var src = img.currentSrc ? img.currentSrc : img.src;

          //To the closest parent with bgFromSrcSet class,
          //set the final src as a background-image CSS
          $currImg.closest('.bgFromSrcSet').css('background-image', "url('"+src+"')");

          //remove processed image from the jQuery set
          //(to update $srcSets.length that is checked in the loadChecker)
          $srcSets = $srcSets.not($currImg);

          $currImg.remove(); //remove the <img ...> itself 
      })
    ;      

  });

  //window's load event is called even on following loads...
  $window.load(function(){    
    //prepare the checker
    var loadChecker = setInterval(function(){
        if( $srcSets.length > 0 ) //if there is still work to do...
            $srcSets.load(); //...do it!
        else
            clearInterval(loadChecker); //if there is nothing to do - stop the checker
    }, 150);  
  });

});

HTML

HTML

...could look like this:

...看起来像这样:

<div class="bgFromSrcSet">
  <img class="srcSet"
       alt=""
       src="http://example.com/something.jpeg" 
       srcset="http://example.com/something.jpeg 5760w, http://example.com/something-300x200.jpeg 300w, http://example.com/something-768x512.jpeg 768w, http://example.com/something-1024x683.jpeg 1024w, http://example.com/something-1000x667.jpeg 1000w"
       sizes="(max-width: 2000px) 100vw, 2000px"
  >
  Something else...
</div>

Note:class bgFromSrcSetmust notbe set to the imgitself! It can only be set to the elements in the imgDOM parent tree.

注:bgFromSrcSet必须设置为img自己!它只能设置为imgDOM 父树中的元素。

回答by Martti Hyv?nen

If you are using Foundation framework (https://foundation.zurb.com/), you can use Interchange plugin for that:

如果您使用 Foundation 框架(https://foundation.zurb.com/),您可以使用 Interchange 插件:

<div data-interchange="[assets/img/interchange/small.jpg, small], 
                       [assets/img/interchange/medium.jpg, medium], 
                       [assets/img/interchange/large.jpg, large]">
</div>

https://foundation.zurb.com/sites/docs/interchange.html#use-with-background-images

https://foundation.zurb.com/sites/docs/interchange.html#use-with-background-images