首页 > 解决方案 > 当浏览器允许和不加载 png 时,如何为 background-img 加载 webp 图像?

问题描述

如果浏览器允许,我正在尝试创建一个使用 webp 图像作为背景的标题,但是当我不希望浏览器加载 png 时。

这是我的 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>

这是我到目前为止的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);
}

但我不知道如何将所有东西联系在一起,知道吗?

标签: javascripthtmljquerycss

解决方案


如果 php 是一个选项,我建议使用这个:

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

如果你需要通过 JS 来做,那么看看这个


推荐阅读