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

后端 未结 10 2189
鱼传尺愫
鱼传尺愫 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:14

    Extract key/value pairs from a complex transform string:

    using regex.exec method

    If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property). Note that the lastIndex property will not be reset when searching a different string, it will start its search at its existing lastIndex.

    function parseComplexStyleProperty( str ){
       var regex = /(\w+)\((.+?)\)/g, transform = {}, match;
    
       while( match = regex.exec(str) )
           transform[match[1]] = transform[match[1]] 
               ? transform[match[1]].concat([match[2]])
               : [match[2]]
      
       return transform
    }
    
    
    /// USAGE: ///////////////////////////////////////
    
    var dummyString = "translateX(-50%) translateX(100px) scale(1.2)",
        transformObj = parseComplexStyleProperty(dummyString);
    
    console.log(transformObj)

    Note - mind that this is also a valid CSS transform value:

    translateX(-50%) translateX(100px);
    

    More Complex Cases:

    function parseTransform(s){ 
      var keys = ['matrix3d', 'matrix', 'perspective', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'rotate', 'translate3d', 'translateX', 'translateY', 'translateZ', 'translate', 'scale3d', 'scaleX', 'scaleY', 'scaleZ', 'scale', 'skewX', 'skewY',  'skew'];
    
      return (s+'    ').replace(  new RegExp( '\\b' + keys.join('|') + '\\b','gi'), m => '    ' +m)
      .split(')    ').reduce((acc, p) => {
        p = p.trim()
    
        var name = p.slice(0, p.indexOf('(')),
            value = p.slice(p.indexOf('(') + 1, 999)
    
        if(!p) return acc
       
        if( acc[name] ) 
          acc[name].push(value)
        else 
          acc[name] = [value]
    
        return acc
      }, {})
    }
    
    
    console.log(
    parseTransform('scale(1.2 0.5) rotate(var(--c1) var(--c2)) translateX(-50%) translateX(100px)')
    )

    0 讨论(0)
  • 2020-12-14 19:17

    I thought of one possibility. If you're prepared to parse strings in JavaScript, use

    data=document.getElementById("myDiv").getAttribute("-webkit-transform");

    then interpret data.

    0 讨论(0)
  • 2020-12-14 19:19

    Since you only get the final matrix value from the computed style, you might have to check the element's inline style or stylesheet rules. If element.style.webkitTransform gives you nothing, you might to iterate through the document's stylesheets, and see which one matches your element. Then you can regex the webkitTransform property to get/set the value.

    0 讨论(0)
  • 2020-12-14 19:20

    This link from Apple Dev Reference might shed more light on the subject:

    The webkitTransform property is a string representation of a list of transform operations. Usually this list contains a single matrix transform operation. For 3D transforms, the value is "matrix3d(...)" with the 16 values of the 4x4 homogeneous matrix between the parentheses. For 2D transforms, the value is a "matrix(...)" string containing the 6 vector values.

    0 讨论(0)
  • 2020-12-14 19:20

    you can use regex to get a map of property-value:

    if variable transformstyle contains the style value

      //get all transform declarations
     (transformstyle.match(/([\w]+)\(([^\)]+)\)/g)||[]) 
          //make pairs of prop and value         
         .map(function(it){return it.replace(/\)$/,"").split(/\(/)})
         //convert to key-value map/object         
         .reduce(function(m,it){return m[it[0]]=it[1],m},{})
    

    for:

    var transformstyle="-webkit-transform: scale(1.1) rotateY(7deg) translateZ(-1px)"
    

    you would get:

    {scale: "1.1", rotateY: "7deg", translateZ: "-1px"}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题