How to read/parse individual transform style values in JavaScript?

后端 未结 10 2211
鱼传尺愫
鱼传尺愫 2020-12-14 18:34

Webkit\'s blog post from last year on 3D transforms explains the various transform \'functions\' that can be used in the -webkit-transform property. For example:

<         


        
10条回答
  •  甜味超标
    2020-12-14 19:23

    // Suppose the transformed element is called "cover".
    var element = document.getElementById('cover');
    computedStyle = window.getComputedStyle(element, null); // "null" means this is not a pesudo style.
    // You can retrieve the CSS3 matrix string by the following method.
    var matrix = computedStyle.getPropertyValue('transform')
        || computedStyle.getPropertyValue('-moz-transform')
        || computedStyle.getPropertyValue('-webkit-transform')
        || computedStyle.getPropertyValue('-ms-transform')
        || computedStyle.getPropertyValue('-o-transform');
    
    // Parse this string to obtain different attributes of the matrix.
    // This regexp matches anything looks like this: anything(1, 2, 3, 4, 5, 6);
    // Hence it matches both matrix strings:
    // 2d: matrix(1,2,3,4,5,6)
    // 3d: matrix3d(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
    var matrixPattern = /^\w*\((((\d+)|(\d*\.\d+)),\s*)*((\d+)|(\d*\.\d+))\)/i;
    var matrixValue = [];
    if (matrixPattern.test(matrix)) { // When it satisfy the pattern.
        var matrixCopy = matrix.replace(/^\w*\(/, '').replace(')', '');
        console.log(matrixCopy);
        matrixValue = matrixCopy.split(/\s*,\s*/);
    }
    

    Hope this helps! Note that I did not use another library except plain DOM API and native Javascript RegExp function. Hence, this should work universally cross browsers and application.

提交回复
热议问题