Html 检测“转换:translate3d”支持

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5661671/
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-08-29 07:57:56  来源:igfitidea点击:

Detecting 'transform: translate3d' support

htmlcss

提问by Jamie

Does anyone know how I would detect transform: translate3d(x,y,z)support is available?

有谁知道我将如何检测transform: translate3d(x,y,z)支持是否可用?

My issue is that I want to use translate3dacross browsers where it is supported because it tends to use hardware acceleration and hence smoother for animation, and then fall back to translatewhere its not.

我的问题是我想translate3d在支持它的浏览器中使用它,因为它倾向于使用硬件加速,因此动画更流畅,然后又回到translate不支持的地方。

回答by Lorenzo Polidori

Check out this solution.

看看这个解决方案

It is based on the fact that if a browser supports transforms, the value of

它基于这样一个事实,如果浏览器支持转换,则

window.getComputedStyle(el).getPropertyValue('transform')

will be a string containing the transformation matrix, when a 3d transform is applied to the element el. Otherwise, it will be undefinedor the string 'none', as in the case of Opera 12.02.

当 3d 变换应用于元素时,将是一个包含变换矩阵的字符串el。否则,它将是undefined或 string 'none',如 Opera 12.02 的情况。

It works on all major browsers.

它适用于所有主要浏览器。

The code:

编码:

function has3d() {
    if (!window.getComputedStyle) {
        return false;
    }

    var el = document.createElement('p'), 
        has3d,
        transforms = {
            'webkitTransform':'-webkit-transform',
            'OTransform':'-o-transform',
            'msTransform':'-ms-transform',
            'MozTransform':'-moz-transform',
            'transform':'transform'
        };

    // Add it to the body to get the computed style.
    document.body.insertBefore(el, null);

    for (var t in transforms) {
        if (el.style[t] !== undefined) {
            el.style[t] = "translate3d(1px,1px,1px)";
            has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
        }
    }

    document.body.removeChild(el);

    return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}

回答by Jonathan Tran

The original blog post announcing 3D transformshas an image flip demo, which does it with a media query, like this:

宣布 3D 变换原始博客文章有一个图像翻转演示,它使用媒体查询来完成,如下所示:

@media all and (-webkit-transform-3d) {
  /* Use the media query to determine if 3D transforms are supported */
  #flip-container {
    -webkit-perspective: 1000;
  }
  #flip-card {
    width: 100%;
    height: 100%;
    -webkit-transform-style: preserve-3d;
    -webkit-transition: -webkit-transform 1s;
  }
  #flip-container:hover #flip-card {
    -webkit-transform: rotateY(180deg);
  }
}

This blog posthas a good intro to media queries. Thishas some more details.

这篇博文很好地介绍了媒体查询。 还有一些细节。

回答by Vitalii Fedorenko

You can try CCS3 @supports:

你可以试试 CCS3 @supports

@supports (transform: translate3d) {
  div {
    transform : translate3d(20px,0,0);
  }
}

@supports not (transform: translate3d) {
  div {
    transform: translate(20px,0);
  }
}

Can I use @support

我可以使用@support

回答by Spudley

I'd suggest using Modernizr.

我建议使用Modernizr

It does feature detection for a whole range of browser features, including 3D transforms. It also provides a method of specifying CSS rules for browsers which have various features or not, so it sounds like it will do exactly what you're looking for.

它对一系列浏览器功能进行特征检测,包括 3D 变换。它还提供了一种为具有各种功能或不具有各种功能的浏览器指定 CSS 规则的方法,因此听起来它可以完全满足您的要求。

Hope that helps.

希望有帮助。

回答by elrasguno

//The following is based on iScroll4's tests to determine if a browser supports CSS3 3D     transforms.
var has3d = function() {
    return ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix());
}

回答by souporserious

Was tinkering around with a way to check for 3d support.. used this implementation from Jeffery Way in this article. Allows for less code and more use cases ;)

正在修补一种检查 3d 支持的方法.. 在本文中使用了 Jeffery Way 的这个实现。允许更少的代码和更多的用例;)

/**
* Test For CSS3 property support
* use 'perspective' to test for 3d support
*/
var supports = (function() {

    'use strict';

    var div = document.createElement('div'),
        vendors = 'Khtml ms O Moz Webkit'.split(' '),
        len = vendors.length;

    return function(prop) {

        if (prop in div.style) return true;

        prop = prop.replace(/^[a-z]/, function(val) {
            return val.toUpperCase();
        });

        while(len--) {
            if (vendors[len] + prop in div.style) {
                return true;
            } 
        }

        return false;
    };
})();

if(supports('perspective')) {
    // do 3d stuff
}

回答by Sergej

Bootstrap uses following Code:

Bootstrap 使用以下代码:

@media all and (transform-3d), (-webkit-transform-3d) {
    .carousel-inner > .carousel-item {
        transition: transform 0.6s ease-in-out;
        backface-visibility: hidden;
        perspective: 1000px;
    }
    .carousel-inner > .carousel-item.next,
    .carousel-inner > .carousel-item.active.right {
        left: 0;
        transform: translate3d(100%, 0, 0);
    }
    .carousel-inner > .carousel-item.prev,
    .carousel-inner > .carousel-item.active.left {
        left: 0;
        transform: translate3d(-100%, 0, 0);
    }
    .carousel-inner > .carousel-item.next.left,
    .carousel-inner > .carousel-item.prev.right,
    .carousel-inner > .carousel-item.active {
        left: 0;
        transform: translate3d(0, 0, 0);
    }
}

回答by Dan

This code is adjusted for testing 3D transformssupport and other CSS3 features.

调整此代码以测试3D 转换支持和其他 CSS3 功能。

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: 'translateZ(0.5em) rotateY(10deg) scale(2)'
           // This will test for 3D transform support
           // Use translateX to test 2D 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;
            }
        }
    }

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

回答by Brennan Moore

tl:dr - Use user agent sniffing. Here is a script for detecting CSS 3D transform support across browsers: https://github.com/zamiang/detect-css3-3D-transform

tl:dr - 使用用户代理嗅探。这是用于检测跨浏览器的 CSS 3D 转换支持的脚本:https: //github.com/zamiang/detect-css3-3D-transform

I tried most of the methods in this post, among others like Modernizerand Meny's methods but could not support browsers like Firefox while maintaining a good experience for older browsers like Safari 4&5, iOS devices and Chrome on Retina MacBook pros (they all have their quirks).

我尝试了这篇文章中的大部分方法,其中包括ModernizerMeny的方法,但无法支持 Firefox 等浏览器,同时在 Retina MacBook pro 上对 Safari 4&5、iOS 设备和 Chrome 等旧浏览器保持良好体验(它们都有他们的怪癖)。

CSS3 3D transforms involve interaction between the browser and the graphics card. The browser may be able to parse the 3D declarations but may not be able to properly instruct the graphics card in how to render your page. There are many possible outcomes ranging from the page rendering with lines across it (Safari 4) to the page rendering beautifully then crashing the browser seconds later (Safari on iOS4). Any ‘feature detection' approach would unacceptably flag these as ‘supports CSS3 3D transforms'. This is one case where ‘feature detection' fails and user agent sniffing (and lots of testing) wins hands down.

CSS3 3D 转换涉及浏览器和显卡之间的交互。浏览器可能能够解析 3D 声明,但可能无法正确指示图形卡如何呈现您的页面。有许多可能的结果,从页面渲染(Safari 4)到漂亮的页面渲染然后几秒钟后浏览器崩溃(iOS4 上的 Safari)。任何“特征检测”方法都会不可接受地将这些标记为“支持 CSS3 3D 转换”。这是“功能检测”失败并且用户代理嗅探(和大量测试)获胜的一种情况。

Most feature detection assumes a 'supports' or 'does not support' binary. This is not the case with CSS3 3D Transforms - there is a 'gradient of support'.

大多数特征检测假定“支持”或“不支持”二进制。CSS3 3D 变换不是这种情况——有一个“支持梯度”。

CSS3 3D transform support can be separated into 4 levels:

CSS3 3D 变换支持可以分为 4 个级别:

  1. Reliably supports 3D transforms across most machines. For example: Safari 6
  2. Can parse and apply 3D transform declarations but ignores the 3D parts. For example: Chrome on a Retina MacBook Pro.
  3. Can parse and apply 3D transform declarations but renders in unacceptable ways. For example: Safari 4 and Safari 4/5 on Windows show lines across the page.
  4. Cannot apply 3D transform declarations in any way. For example: IE or Firefox < v10
  1. 可靠地支持大多数机器上的 3D 转换。例如:Safari 6
  2. 可以解析和应用 3D 变换声明,但会忽略 3D 部分。例如:Retina MacBook Pro 上的 Chrome。
  3. 可以解析和应用 3D 转换声明,但以不可接受的方式呈现。例如:Windows 上的 Safari 4 和 Safari 4/5 在页面上显示线条。
  4. 不能以任何方式应用 3D 变换声明。例如:IE 或 Firefox < v10

This scriptwill return truein scenario one and two but falsefor 3 and 4:

此脚本true在场景 1 和 2 中返回,但false对于 3 和 4:

Note: new to participating in stackoverflow - please let me know if I should paste that code inline (it is a bit long)

注意:参与 stackoverflow 的新手 - 请告诉我是否应该内联粘贴该代码(有点长)

回答by gcdev

Using jQuery:

使用jQuery:

var cssTranslate3dSupported = false;
(function()
{
    var div = $('<div style="position:absolute;">Translate3d Test</div>');
    $('body').append(div);
    div.css(
    {
        'transform' : "translate3d(20px,0,0)",
        '-moz-transform' : "translate3d(20px,0,0)",
        '-webkit-transform' : "translate3d(20px,0,0)",
        '-o-transform' : "translate3d(20px,0,0)",
        '-ms-transform' : "translate3d(20px,0,0)"
    });
    cssTranslate3dSupported = (div.offset().left == 20);
    div.empty().remove();
})();