检测对背景大小的支持:封面

Detect support for background-size: cover

本文关键字:支持 封面 背景 检测      更新时间:2023-09-26

检测支持CSS3背景大小的保存方法是什么:cover,尤其是在IE<9?

以下测试在IE<9,因为它实际上将背景大小设置为封面

div.style.backgroundSize = 'cover';

我在测试时得到的唯一真实结果

if ('backgroundSize' in div.style)

但据网站介绍http://www.standardista.com/css3/css3-background-properties/#bg11,IE 6/7/8应返回auto,不支持仅覆盖包含

编辑:

我想使用我自己的解决方案,但我已经检查了Modernizr使用的代码。他们似乎使用了在IE<9:设置backgroundSize='cover',然后检查style.backgroundSize=='cover'

看看我的JSFiddle。

如果使用Modernizr,则只能下载执行此类任务所需的代码

http://modernizr.com/download/#-后台大小测试道具测试道具domprefix

然后你可以用测试

if (Modernizr.backgroundsize) {
    /* backgroundSize supported */
}

如果您试图检测功能低下的浏览器,以避免邮票图像卡在中间,那么一个快速而肮脏的解决方法是

var rules = document.styleSheets[0].cssRules;

如果它是未定义的,那么你知道你的浏览器功能低下,可能应该采用后备方法。YMMV。

在设置BackgroundSize之前,您需要检查它是否作为样式属性存在。

var supported = ('backgroundSize' in document.documentElement.style);
if(supported){
    var temp = document.createElement('div');
    temp.style.backgroundSize = 'cover';
    supported = temp.style.backgroundSize == 'cover';
};
return supported;

来源:http://upshots.org/javascript/javascript-detect-support-for-background-size-cover

在此之前,您可能还想尝试使用CSS.supports()进行检测。参见MDN:https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports

这是单独使用javascript,没有jquery,只需检查您使用删除的浏览器版本

//check if Is bad IE. 
var noBGSizeSupport = window.attachEvent && !window.addEventListener 
if(noBGSizeSupport){
    //does not support BG size property
} else {
  // supports background size property
}