检测浏览器中的flex-wrap支持

我正在开发一个项目,其中我有一个响应网格,我已经使用flex wrap属性实现了。 由于我支持IE9和更低版本的Firefox,版本28及更低版本,我如何通过javascript找到对它的支持。 目前我只能通过条件语句识别IE9浏览器,但现在有人如何通过javascript检测Firefox旧版本。

我现在不知道你是怎么做的,但真的没有理由重新发明轮子。

Modernizr( http://modernizr.com/ )就是为此而构建的,是一个广泛使用的特征检测库。 查看CSSfunction,他们支持检测flexbox( http://modernizr.com/docs/#features-css ),并将一直工作回到IE6。

我发现这是最简单的方法:

 var d = document.documentElement.style if (('flexWrap' in d) || ('WebkitFlexWrap' in d) || ('msFlexWrap' in d)){ alert('ok'); } 

我也试过hasOwnProperty但它在IE和FF中不起作用。 那么为什么当你只有3行js时可以使用40 KB的modernizr?

CSS属性检测

一个简单的CSS属性检测技术是直接在一个元素上测试它并检查它是否返回undefined如下所示,

element.style. != undefined

最简单的方法(但有限的支持)

上面的方法直接检查属性,对于大多数常见属性(不适用于flex-wrap)应该足够了。

 function isStyleSupported(el, property) { return el.style[property] != undefined; } var testEl = document.getElementById('test'); testEl.innerHTML = (isStyleSupported(testEl, 'flexWrap')) ? "Flex Wrap is supported" : "Flex Wrap is NOT supported"; 
 

扩展@ AndresTet的答案,如果你不想要一个完整的modernizr构建,你可以创建一个自定义的 ,或者提取和重构相关的flexbox测试,它们似乎是:

 function testPropsAll(prop, prefixed, elem) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); if (is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } tests['flexbox'] = function() { return testPropsAll('flexWrap'); }; tests['flexboxlegacy'] = function() { return testPropsAll('boxDirection'); };