このコードは、 2D 変換のサポートをテストします。
代わりに、 3D 変換のサポートを検出するように簡単に調整できます。CSS をテストするには、'translateZ(1)' を追加するだけです (defaultTestValues
ソース コードを参照)。
このコードの利点は、サポートされているベンダー プレフィックス (存在する場合) を検出することです。あれを呼べ:
testCSSSupport('transform')
可能な戻り値:
false
、機能がサポートされていない場合、または
{
vendor: 'moz',
cssStyle: '-moz-transform',
jsStyle: 'MozTransform'
}
機能がサポートされている場合
/**
* Test for CSS3 feature support. Single-word properties only by now.
* This function is not generic, but it works well for transition and transform at least
*/
testCSSSupport: function (feature, cssTestValue/* optional */) {
var testDiv,
featureCapital = feature.charAt(0).toUpperCase() + feature.substr(1),
vendors = ['', 'webkit', 'moz', 'ms'],
jsPrefixes = ['', 'Webkit', 'Moz', 'ms'],
defaultTestValues = {
transform: 'translateX(.5em)'
// This will test for 2D transform support
// Add translateZ(1) to test 3D transform
},
testFunctions = {
transform: function (jsProperty, computed) {
return computed[jsProperty].substr(0, 9) === 'matrix3d(';
}
};
function isStyleSupported(feature, jsPrefixedProperty) {
if (jsPrefixedProperty in testDiv.style) {
var testVal = cssTestValue || defaultTestValues[feature],
testFn = testFunctions[feature];
if (!testVal) {
return false;
}
//Assume browser without getComputedStyle is either IE8 or something even more poor
if (!window.getComputedStyle) {
return false;
}
testDiv.style[jsPrefixedProperty] = testVal;
var computed = window.getComputedStyle(testDiv);
if (testFn) {
return testFn(jsPrefixedProperty, computed);
}
else {
return computed[jsPrefixedProperty] === testVal;
}
}
}
var cssPrefixedProperty,
jsPrefixedProperty,
testDiv = document.createElement('div');
for (var i = 0; i < vendors.length; i++) {
if (i === 0) {
cssPrefixedProperty = feature; //todo: this code now works for single-word features only!
jsPrefixedProperty = feature; //therefore box-sizing -> boxSizing won't work here
}
else {
cssPrefixedProperty = '-' + vendors[i] + '-' + feature;
jsPrefixedProperty = jsPrefixes[i] + featureCapital;
}
if (isStyleSupported(feature, jsPrefixedProperty)) {
return {
vendor: vendors[i],
cssStyle: cssPrefixedProperty,
jsStyle: jsPrefixedProperty
};
}
}
return false;
}