简体   繁体   中英

Detect support for background-size: cover

What is a save way to detect support for CSS3 background-size: cover , especially in IE < 9?

Following test returns a false positive in IE < 9, because it actually sets background-size to cover :

div.style.backgroundSize = 'cover';

The only true result I get when testing for:

if ('backgroundSize' in div.style)

But according to the site http://www.standardista.com/css3/css3-background-properties/#bg11 , IE 6/7/8 should return auto , only cover and contain are not supported.

Edit:

I would like to use my own solution, but I have checked the code used by Modernizr . It seems they use the same technique that gives me false positive results in IE < 9: Set backgroundSize = 'cover' and then check for style.backgroundSize == 'cover' .

See my JSFiddle .

If you use Modernizr you can download only the code necessary to perform this kind of task

http://modernizr.com/download/#-backgroundsize-testprop-testallprops-domprefixes

then you can test with

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

If you are trying to detect low functioning browsers to avoid having a postage stamp image stuck in the middle of things, then one quick and dirty workaround is to

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

If it's undefined, then you know you have a low functioning browser and should probably go with your fallback approach. YMMV.

You need to check if BackgroundSize exists as a style property before you set it.

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;

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

Before this you might also want to try detection with CSS.supports(). see MDN: https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports

This is with javascript alone, no jquery just check the version of browser you delealing with

//check if Is bad IE. 
var noBGSizeSupport = window.attachEvent && !window.addEventListener 

if(noBGSizeSupport){
    //does not support BG size property
} else {
  // supports background size property
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM