我如何检测浏览器是否支持使用 Javascript(并且不使用modernizr)的 CSS 转换?
问问题
22427 次
5 回答
48
也许是这样的。基本上它只是查看是否transition
定义了 CSS 属性:
function supportsTransitions() {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition';
if (typeof s[p] == 'string') { return true; }
// Tests for vendor specific prop
var v = ['Moz', 'webkit', 'Webkit', 'Khtml', 'O', 'ms'];
p = p.charAt(0).toUpperCase() + p.substr(1);
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
改编自这个要点。所有的功劳都在那里。
于 2011-09-01T00:37:30.030 回答
34
3种方法:
var supportsTransitions = (function() {
var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist
v = ['ms','O','Moz','Webkit']; // 'v' for vendor
if( s['transition'] == '' ) return true; // check first for prefeixed-free support
while( v.length ) // now go over the list of vendor prefixes and check support until one is found
if( v.pop() + 'Transition' in s )
return true;
return false;
})();
console.log(supportsTransitions) // 'true' on modern browsers
或者:
var s = document.createElement('p').style,
supportsTransitions = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
console.log(supportsTransitions); // 'true' on modren browsers
如果您确实想使用正确的前缀,请使用:
function getPrefixed(prop){
var i, s = document.createElement('p').style, v = ['ms','O','Moz','Webkit'];
if( s[prop] == '' ) return prop;
prop = prop.charAt(0).toUpperCase() + prop.slice(1);
for( i = v.length; i--; )
if( s[v[i] + prop] == '' )
return (v[i] + prop);
}
// get the correct vendor prefixed property
transition = getPrefixed('transition');
// usage example
elment.style[transition] = '1s';
于 2012-10-26T05:53:49.150 回答
5
截至 2015 年,这个单线应该可以解决问题(IE 10+、Chrome 1+、Safari 3.2+、FF 4+ 和 Opera 12+):-
var transitionsSupported = ('transition' in document.documentElement.style) || ('WebkitTransition' in document.documentElement.style);
于 2015-04-12T15:19:06.793 回答
2
这里是我使用的方式:
var style = document.documentElement.style;
if (
style.webkitTransition !== undefined ||
style.MozTransition !== undefined ||
style.OTransition !== undefined ||
style.MsTransition !== undefined ||
style.transition !== undefined
)
{
// Support CSS3 transititon
}
于 2013-05-19T09:28:07.220 回答
0
您也可以使用以下方法(一种单线功能):
var features;
(function(s, features) {
features.transitions = 'transition' in s || 'webkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s;
})(document.createElement('div').style, features || (features = {}));
console.log(features.transitions);
于 2013-01-23T09:24:33.450 回答