使用 JavaScript 或 jQuery 检测 CSS 转换 2D 是否可用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7212102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:19:05  来源:igfitidea点击:

Detect with JavaScript or jQuery if CSS transform 2D is available

javascriptjquerycsscss-transforms

提问by Poru

I'm displaying a element on my site which I rotate with -90deg but if a browser doesn't support the CSS transform the element looks misspositioned and not really good. Now I want to detect with JavaScript or jQuery (it's indifferent if jQ or JS because I use/loaded already jQ on my site) if this rotation via CSS is supported?

我正在我的网站上显示一个元素,该元素以 -90deg 旋转,但如果浏览器不支持 CSS 转换,则该元素看起来位置错误并且不太好。现在我想用 JavaScript 或 jQuery 检测(jQ 或 JS 无关紧要,因为我在我的网站上使用/加载了 jQ)是否支持通过 CSS 进行的这种旋转?

I know Modernizrbut just for that little thing I don't want to include that whole library (and speed down the website speed load).

我知道Modernizr但只是为了那件小事,我不想包含整个库(并降低网站速度加载)。

回答by Roshambo

Here's a function based on Liam's answer. It will return either the name of the first supported prefix or falseif none of the prefixes are supported.

这是一个基于 Liam 的回答的函数。它将返回第一个支持的前缀的名称,或者false如果不支持任何前缀。

function getSupportedTransform() {
    var prefixes = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' ');
    var div = document.createElement('div');
    for(var i = 0; i < prefixes.length; i++) {
        if(div && div.style[prefixes[i]] !== undefined) {
            return prefixes[i];
        }
    }
    return false;
}

回答by Lime

This is about as simple as you get and a jsfiddle. It no longer goes on an infinite loop.

这和你得到的一样简单,还有一个jsfiddle。它不再无限循环。

function getSupportedTransform() {
    var prefixes = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' ');
    for(var i = 0; i < prefixes.length; i++) {
        if(document.createElement('div').style[prefixes[i]] !== undefined) {
            return prefixes[i];
        }
    }
    return false;
}

回答by jfriend00

Here's the code I'm using to detect if CSS3 transitions are supported:

这是我用来检测是否支持 CSS3 转换的代码:

var div = document.createElement('div');
div.setAttribute('style', 'transition:top 1s ease;-webkit-transition:top 1s ease;-moz-transition:top 1s ease;-o-transition:top 1s ease;');
document.body.appendChild(div);
var cssTransitionsSupported = !!(div.style.transition || div.style.webkitTransition || div.style.MozTransition || div.style.OTransitionDuration);

div.parentNode.removeChild(div);
div = null;

I'm purposefully not looking for Microsoft support since Microsoft hasn't yet shipped a browser that supports CSS3 transitions and I don't want my code automatically supporting an implementation I haven't tested yet in the future.

我故意不寻求 Microsoft 支持,因为 Microsoft 尚未发布支持 CSS3 转换的浏览器,而且我不希望我的代码自动支持我将来尚未测试的实现。

回答by wesbos

Just pull what you need out of Modernizr

只需从 Modernizr 中提取您需要的东西

First we need the testProps function

首先我们需要 testProps 函数

   /**
     * testProps is a generic CSS / DOM property test; if a browser supports
     *   a certain property, it won't return undefined for it.
     *   A supported CSS property returns empty string when its not yet set.
     */
    function testProps( props, prefixed ) {
        for ( var i in props ) {
            if ( mStyle[ props[i] ] !== undefined ) {
                return prefixed == 'pfx' ? props[i] : true;
            }
        }
        return false;
    }

Then run the cssTransform test

然后运行 ​​cssTransform 测试

var tests = [];
 tests['csstransforms'] = function() {
        return !!testProps(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);
    };

if tests['csstransforms'] is true, then you have the feature available.

如果 tests['csstransforms'] 为真,那么您就有了可用的功能。

回答by Dan

This code tests for 2D transformssupport.

此代码测试2D 转换支持。

It can be easily adjusted to detect 3D transformssupport instead. Just add 'translateZ(1)' to test CSS (see defaultTestValuesin source code).

可以轻松调整它以检测3D 转换支持。只需添加 'translateZ(1)' 来测试 CSS(参见defaultTestValues源代码)。

The plus of this code is that it detects the vendor prefix supported (if any). Call it:

此代码的优点是它检测支持的供应商前缀(如果有)。称它为:

testCSSSupport('transform')

Possible return values:

可能的返回值:

false, when feature unsupported, or

false,当功能不受支持时,或

{
    vendor: 'moz',
    cssStyle: '-moz-transform',
    jsStyle: 'MozTransform'
}

when feature supported

当功能支持时

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