首页 > 解决方案 > Modernizr:如果不支持,则在后台删除带有 .webp 的元素

问题描述

我有一个使用 Modernizr.js 的简单代码,它可以帮助我检测用户浏览器是否支持 .webp。

我在<head>部分中使用此代码可以保证我在其他脚本之前加载。

我有 2 个相同的 html 元素,其中一个在背景中使用 .webp,第二个是 .jpg。

现在我需要 modernizr.js 将检测是否检测到 .webp 并隐藏具有 .jpg 背景的元素。并切换它。

现在,当不支持 webp 时,我的 Javascript 不会删除带有 webp 背景的 html 元素。

有什么解决方案如何修复它或者我是否正确使用它?

我的代码:

Modernizr.on('webp', function(result) {
  if (result) {
    document.getElementsByClassName("no-webp").remove();
  } else {
    document.getElementsByClassName("webp").remove();
  }
});
section {
  height: 200px;
  width: 200px;
}

section.webp {
  background: url('http://superweb.online/assets/img/mainbg.webp') no-repeat;
  background-size: cover;
}

section.no-webp {
  background: url('http://superweb.online/assets/img/mainbg.jpg') no-repeat;
  background-size: cover;
}
<script src="http://superweb.online/assets/js/modernizr-custom.js"></script>
<section class="webp"></section>
<section class="no-webp"></section>

标签: javascripthtmlmodernizr

解决方案


如果没有 webp 支持,您可以使用自动回退到 .jpg 的回退机制picture

<picture>
   <source srcset="http://superweb.online/assets/img/mainbg.webp" type="image/webp" />
   <img src="http://superweb.online/assets/img/mainbg.jpg" />
</picture>

如果没有支持,浏览器将自动使用旧图像。它实际上更快,特别是如果用户的互联网连接速度较慢。

这里不需要javascript。

仅在图像标签上应用您的 CSS


推荐阅读