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

发布于 2024-12-01 19:25:55 字数 261 浏览 1 评论 0原文

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

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

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

空城仅有旧梦在 2024-12-08 19:25:55

这是一个基于利亚姆答案的函数。它将返回第一个受支持的前缀的名称,如果不支持任何前缀,则返回 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;
}

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

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;
}
薄荷→糖丶微凉 2024-12-08 19:25:55

这就像你得到的一样简单,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;
}

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

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;
}
遗弃M 2024-12-08 19:25:55

以下是我用来检测是否支持 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;

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

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

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.

长梦不多时 2024-12-08 19:25:55

只需从 Modernizr 中提取您需要的内容

首先我们需要 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;
    }

然后运行 ​​cssTransform 测试

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

如果tests['csstransforms']为true,那么您就可以使用该功能。

Just pull what you need out of Modernizr

First we need the testProps function

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

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

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

空城之時有危險 2024-12-08 19:25:55

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

它可以轻松调整以检测 3D 变换 支持。只需添加“translateZ(1)”即可测试 CSS(请参阅源代码中的 defaultTestValues)。

该代码的优点是它可以检测支持的供应商前缀(如果有)。调用它:

testCSSSupport('transform')

可能的返回值:

false,当功能不支持时,或

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

当功能支持时

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

This code tests for 2D transforms support.

It can be easily adjusted to detect 3D transforms support instead. Just add 'translateZ(1)' to test CSS (see defaultTestValues in source code).

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

{
    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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文