javascript - 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>
解决方案
如果没有 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
推荐阅读
- neo4j - Neo4j cypher - 单一关系查询中的单向和双向?
- c++ - For 循环方法调用
- java - Socket.setTcpNoDelay() 与主机设置(Nagle 算法)
- android - 在 CMAKE 中包含来自 Android 项目的不同文件夹的静态库
- java - AsyncRabbitTemplate 与 SyncRabbitTemplate :实践中有什么区别?
- c# - 实体框架使用错误的字符串编码?
- ios - IBDesignable 类未在 xcode 中更新
- google-apps-script - 如何避免仅限我使用的私有脚本的受限范围 OAuth 验证过程?
- acumatica - Acumatica - 图形扩展和屏幕重命名
- javascript - 在 Fullcalendar 的月视图中更改一行的高度