如何测试剪辑路径支持?

8 css cross-browser modernizr

clip-path:shape()似乎不适用于IE(毫不奇怪)和Firefox(有点惊讶).有没有办法测试剪辑路径支持?我用的是modernizr.(顺便说一句,我知道我可以使用SVG来实现这一点-webkit-clip-path:url(#mySVG))

jwe*_*est 17

你刚才问过这个问题,说实话,我不确定Modernizr是否还没有为此添加支持,但在这种情况下你很容易推出自己的测试.

步骤是:

  1. 创建但不附加DOM元素.
  2. 通过检查style新创建的元素的JS 属性(element.style.clipPath === ''如果它可以支持它)来检查它是否支持任何类型的clipPath .
  3. 通过使element.style.clipPath一些有效的CSS剪辑路径形状相等来检查它是否支持CSS剪辑路径形状.

当然,它比这更复杂,因为您必须检查供应商特定的前缀.

这一切都在一起:

var areClipPathShapesSupported = function () {

    var base = 'clipPath',
        prefixes = [ 'webkit', 'moz', 'ms', 'o' ],
        properties = [ base ],
        testElement = document.createElement( 'testelement' ),
        attribute = 'polygon(50% 0%, 0% 100%, 100% 100%)';

    // Push the prefixed properties into the array of properties.
    for ( var i = 0, l = prefixes.length; i < l; i++ ) {
        var prefixedProperty = prefixes[i] + base.charAt( 0 ).toUpperCase() + base.slice( 1 ); // remember to capitalize!
        properties.push( prefixedProperty );
    }

    // Interate over the properties and see if they pass two tests.
    for ( var i = 0, l = properties.length; i < l; i++ ) {
        var property = properties[i];

        // First, they need to even support clip-path (IE <= 11 does not)...
        if ( testElement.style[property] === '' ) {

            // Second, we need to see what happens when we try to create a CSS shape...
            testElement.style[property] = attribute;
            if ( testElement.style[property] !== '' ) {
                return true;
            }
        }
    }

    return false;
};
Run Code Online (Sandbox Code Playgroud)

这是一个代码概念验证:http://codepen.io/anon/pen/YXyyMJ