该问题不仅限于 Firefox<=23,还发生在 Safari<7 iOS<7 和 IE<=11 上,因此我创建了一个更通用的解决方案,它还支持转换延迟和多个以逗号分隔的声明,例如:
transition: transform 1500ms cubic-bezier(0,0.6,1) 1s, left 500ms;
这是我的 jQuery 插件和辅助函数:
/**
* PROBLEM: FF<=23, IE<=11 and Safari<7 return empty strings on
* $elm.css('-prefix-transition').
* SOLUTION: Retrieve transition properties separately and compose full version.
*
* See answer at http://stackoverflow.com/a/21139827/328272.
*/
jQuery.fn.getTransitionStyle = function(transitionPrefixed) {
var $elm = this;
if ($elm.css(transitionPrefixed)) return $elm.css(transitionPrefixed);
// Transition properties to iterate through.
var properties = 'property duration timing-function delay'.split(' '),
result = [], valueArray, i, j;
// Iterate through transition properties.
for (i = 0; i < properties.length; i++) {
// Get property value and split by comma.
valueArray = $.css($elm[0], transitionPrefixed + '-' + properties[i]).splitCssStyleByComma();
// Iterate through
for (j = 0; j < valueArray.length; j++) {
// Add value to return array.
result[j] = (result[j] ? result[j] + ' ' : '') + valueArray[j];
}
}
alert(result.join(', '));
return result.join(', ');
};
/**
* Split CSS style by commas while ignoring commas between parenthesis.
* Example:
* Input string: "transform 1500ms cubic-bezier(0,0.6,1), left 500ms"
* Output array: ["transform 1500ms cubic-bezier(0,0.6,1)", "left 500ms"]
*/
(function() {
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*',
regExpMain = new RegExp(regExpString),
regExpValidate = new RegExp('^(' + regExpString + ')+$'),
string, result;
String.prototype.splitCssStyleByComma = function() {
string = this, result = [];
// DEBUG: Validate value to prevent an infinite loop.
if (!string.match(regExpValidate)) {
console.log('ERROR: Cannot split CSS style by comma: "' + string + '"');
return false;
}
// As long as there is a string left, chop off the parts we desire.
while (string.match(regExpMain)) {
// Add value to return array.
result.push(RegExp.$1);
// Remove value from string.
string = string.replace(regExpMain, '');
}
return result;
};
})();
按以下方式使用插件。我Modernizr.prefixed()
用来查找过渡样式名称的可选前缀版本,但任何其他方法当然可以:
var transitionNamePrefixed = Modernizr.prefixed('transition');
var transitionStyle = $('.element').getTransitionStyle(transitionNamePrefixed);