使用JavaScript检测对转换的支持

时间:2012-06-04 20:54:08

标签: javascript css css3 css-transitions

我想提供不同的javascript文件,具体取决于浏览器是否支持CSS3过渡。有没有比我下面的代码更好的方法来检测转换支持?

window.onload = function () {
    var b = document.body.style;
    if(b.MozTransition=='' || b.WebkitTransition=='' || b.OTransition=='' || b.transition=='') {
        alert('supported');
    } else {
        alert('NOT supported')
    }
}

5 个答案:

答案 0 :(得分:37)

我也认为包括Modernizr是一种矫枉过正。以下功能适用于任何功能。

function detectCSSFeature(featurename){
    var feature = false,
    domPrefixes = 'Webkit Moz ms O'.split(' '),
    elm = document.createElement('div'),
    featurenameCapital = null;

    featurename = featurename.toLowerCase();

    if( elm.style[featurename] !== undefined ) { feature = true; } 

    if( feature === false ) {
        featurenameCapital = featurename.charAt(0).toUpperCase() + featurename.substr(1);
        for( var i = 0; i < domPrefixes.length; i++ ) {
            if( elm.style[domPrefixes[i] + featurenameCapital ] !== undefined ) {
              feature = true;
              break;
            }
        }
    }
    return feature; 
}

var hasCssTransitionSupport = detectCSSFeature("transition");

https://developer.mozilla.org/en-US/docs/CSS/Tutorials/Using_CSS_animations/Detecting_CSS_animation_support启发

答案 1 :(得分:3)

Modernizr会为您检测到这一点。使用this link创建仅包含CSS3 2D和/或3D过渡的自定义下载版本。

运行后,您可以在csstransitions代码(CSS)上测试html课程,也可以在JavaScript中测试Modernizr.csstransitionstrue。< / p>

更多文档:http://modernizr.com/docs/#csstransitions

答案 2 :(得分:1)

这是另一个测试代码。也许这是一种矫枉过正,但该函数试图将CSS属性设置为DOM对象,然后从中读回。

从未在大量异国情调的浏览器上测试此代码,但它比检查CSS属性可用性更安全。啊,是的,它可以区分2D变换支持和3D变换支持!只需传递您想要测试的CSS属性值!

此代码的优点是它检测到支持的供应商前缀(如果有)。可能的返回值:

false,功能不受支持时,或

{
    vendor: 'moz',
    cssStyle: '-moz-transition',
    jsStyle: 'MozTransition'
}

支持功能时

/**
 * 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 for transition and transform */) {
    var testDiv,
        featureCapital = feature.charAt(0).toUpperCase() + feature.substr(1),
        vendors = ['', 'webkit', 'moz', 'ms', 'o'],
        jsPrefixes = ['', 'Webkit', 'Moz', 'ms', 'O'],
        defaultTestValues = {
            transition: 'left 2s ease 1s',
            transform: 'rotateX(-180deg) translateZ(.5em) scale(0.5)'
           // This will test for 3D transform support
           // Use other values if you need to test for 2D support only
        },
        testFunctions = {
            transition: function (jsProperty, computed) {
                return computed[jsProperty + 'Delay'] === '1s' && computed[jsProperty + 'Duration'] === '2s' && computed[jsProperty + 'Property'] === 'left';
            },
            transform: function (jsProperty, computed) {
                return computed[jsProperty].substr(0, 9) === 'matrix3d(';
            }
        };

    /* test given vendor prefix */
    function isStyleSupported(feature, jsPrefixedProperty) {
        if (jsPrefixedProperty in testDiv.style) {
            var testVal = cssTestValue || defaultTestValues[feature],
                testFn = testFunctions[feature];
            if (!testVal) {
                return false;
            }       

            testDiv.style[jsPrefixedProperty] = testVal;
            var computed = window.getComputedStyle(testDiv);

            if (testFn) {
                return testFn(jsPrefixedProperty, computed);
            }
            else {
                return computed[jsPrefixedProperty] === testVal;
            }
        }
        return false;
    }

    //Assume browser without getComputedStyle is either IE8 or something even more poor
    if (!window.getComputedStyle) {
        return false;
    }

    //Create a div for tests and remove it afterwards
    if (!testDiv) {
        testDiv = document.createElement('div');
        document.body.appendChild(testDiv);
        setTimeout(function () {
            document.body.removeChild(testDiv);
            testDiv = null;
        }, 0);
    }

    var cssPrefixedProperty,
        jsPrefixedProperty;

    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;
}

Github:https://github.com/easy-one/CSS3test

答案 3 :(得分:0)

if (window.TransitionEvent){

}

答案 4 :(得分:0)

使用Modernizr 3.0(alpha),您可以在本地生成自定义构建。这可以解决上述&#34;矫枉过正的问题。关注 - 虽然我首先并不完全清楚这个问题(但我假设它的大小)。新的api提供了一个&#39; build&#39;方法,您可以向其传递包含您希望包含在构建中的测试的json。

我在gulp文件中使用了类似的东西,但不需要gulp - 一个简单的节点脚本就可以了。

StorageImpl<T>*

&#39; modernizr-config.json&#39;文件将是

gulp.task('js:modernizr', function() {
    var modConfig = JSON.parse(fs.readFileSync('modernizr-config.json', {
            encoding: 'utf8'
        }));
    modernizr.build(modConfig, function(res) {
        fs.writeFileSync('modernizr.js', res);
        return true;
    });
}); 

完整配置文件包含在Modernizr包中。

通过这种方法,您可以通过软件包安装程序利用维护良好的Modernizr测试套件,并根据需要轻松添加/删除测试。减少测试,显然减小文件。

&#39; setClasses&#39;选项会将相关的测试类添加到您的html中,但您也可以利用3.0异步事件,如下所示:

{
  "classPrefix": "",
  "options": [
    "addTest",
    "atRule",
    "domPrefixes",
    "hasEvent",
    "html5shiv",
    "html5printshiv",
    "load",
    "mq",
    "prefixed",
    "prefixes",
    "prefixedCSS",
    "setClasses",
    "testAllProps",
    "testProp",
    "testStyles"
  ],
  "feature-detects": [
    "css/transforms",
    "css/transforms3d",
    "css/transformstylepreserve3d",
    "css/transitions",
    "touchevents",
    "workers/webworkers",
    "history"
  ]
}