Mã này kiểm tra Biến đổi 2D hỗ trợ.
Có thể dễ dàng điều chỉnh để phát hiện Biến đổi 3D hỗ trợ thay thế. Chỉ cần thêm 'translateZ (1)' để kiểm tra CSS (xem defaultTestValues
trong mã nguồn).
Điểm cộng của mã này là nó phát hiện tiền tố của nhà cung cấp được hỗ trợ (nếu có). Gọi đó là:
testCSSSupport('transform')
giá trị trả lại có thể xảy ra:
false
, khi tính năng không được hỗ trợ, hoặc
{
vendor: 'moz',
cssStyle: '-moz-transform',
jsStyle: 'MozTransform'
}
khi tính năng được hỗ trợ
/**
* 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;
}
Có xem xét nguồn gốc của [jQuery transform plugin] (https://github.com/louisremi/jquery.transform.js/) (mở rộng jQuery '.css()' và '.animate() 'chức năng) làm thế nào họ đã làm nó. Hoặc, tốt hơn, chỉ cần sử dụng plugin đó :) Nó nhỏ. – BalusC
Bạn không cần phải tải xuống toàn bộ gói từ modernizr, bạn chỉ có thể chọn chuyển đổi 2d từ tải xuống tùy chỉnh –
Tôi chỉ xem cách modernizr làm mọi thứ và mượn các phần nhỏ từ nó cho một dự án của tôi. – jfriend00