简体   繁体   English

当浏览器允许和不加载 png 时,如何为 background-img 加载 webp 图像?

[英]How to load a webp image for a background-img when the browser allows it and when not load a png?

I'm trying to create a header that uses a webp image as background if the browser allows it, but when not I want the browser to load a png instead.我正在尝试创建一个 header,如果浏览器允许它使用 webp 图像作为背景,但当我不希望浏览器加载 png 时。

this is the HTML I have这是我的 HTML

<div class="no-webp">
    <section class="section-hero box-container">
        <div class="container">
            <div class="row">
                <div class="col-12 hero-bg">

                </div>
            </div>
        </div>
    </section>
</div>

<div class="webp">
    <section class="section-hero box-container">
        <div class="container">
            <div class="row">
                <div class="col-12 hero-bg">

                </div>
            </div>
        </div>
    </section>
</div>

and this is the CSS I have so far:这是我到目前为止的 CSS:

section.section-hero{
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 296px;
}

.webp section.section-hero {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp);
}

.no-webp section.section-hero {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png);
}

but I can't figure out how to link everything together, any idea?但我不知道如何将所有东西联系在一起,知道吗?

You can check for the browser using the method explained here .您可以使用此处说明的方法检查浏览器。 From there, you could check for the browsers that have it or not and add the relevant class to the HTML element in question.从那里,您可以检查是否有它的浏览器,并将相关的 class 添加到有问题的 HTML 元素。

So you would have a different class for each background image.因此,每个背景图像都会有不同的 class。 For example:例如:

.webp-supported {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp);
}

.webp-not-supported {
  background-image: url(/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png);
}

If php is an option I recommend using this:如果 php 是一个选项,我建议使用这个:

if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false ) {
   // yeah, webp is supported!
}

If you need to do it via JS, then check this one out .如果你需要通过 JS 来做,那么看看这个

The way I'd do it is by using the <picture> tag in HTML.我这样做的方法是使用 HTML 中的<picture>标签。 This will work in every browser, as browsers which do not support the picture tag will just display whatever source is specified in <img> .这适用于所有浏览器,因为不支持picture标签的浏览器只会显示<img>中指定的任何来源。 For example:例如:

<picture>
  <source srcset="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.webp" type="image/webp">
  <source srcset="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png" type="image/png"> 
  <img src="/coe/julio-rodriguez/proyecto/public/img/webp/hero-banner.png" alt="Hero Banner">
</picture>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM