我希望在网页中使用WebP格式的图片作为背景图片。但是我不确定如何在CSS中设置条件,如果浏览器不支持WebP格式,则使用经典的jpg图片。
我找到了这个示例代码,但它不起作用。
.mybackgroundimage {
background-image: url("image.jpg");
background-image: image("image.webp" format('webp'), "image.jpg");
}
我希望在网页中使用WebP格式的图片作为背景图片。但是我不确定如何在CSS中设置条件,如果浏览器不支持WebP格式,则使用经典的jpg图片。
我找到了这个示例代码,但它不起作用。
.mybackgroundimage {
background-image: url("image.jpg");
background-image: image("image.webp" format('webp'), "image.jpg");
}
您必须使用modernizr来检测浏览器是否支持webp格式,然后应用相应的样式。
.no-webp .mybackgroundimage
{
background: url('image.jpg') no-repeat;
}
.webp .mybackgroundimage
{
background: url('image.webp') no-repeat;
}
// 输入
.banner{
background: url(/img/bannerbg.jpg) no-repeat center;
}
// 输出
.banner{
background: url(/img/bannerbg.jpg) no-repeat center;
}
@supports (-webkit-appearance:none){
.banner {
background-image: url(/img/bannerbg.webp);
}
}
- Harden Rahul-webkit-
前缀。 - Andrei Krasutski