Get item scale value?

I am wondering how can I get the element scale value?

I tried $(element).css('-webkit-transform'); which returns matrix(scaleX,0,0,scaleY,0,0); Is there a way to get scaleX and scaleY only?

+21
javascript jquery css3
Apr 09 2018-11-11T00:
source share
4 answers

If this was set using a matrix, I think you cannot with a simple way, but you can easily analyze the value:

 var matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/, matches = $(element).css('-webkit-transform').match(matrixRegex); 

matches[1] will contain scaleX, and matches[2] will contain scaleY. If it is possible that other transformations have also been applied, you need to fine-tune the regex, because now it assumes that all other parameters are 0.

One way to get scale values ​​can be to remove any transformations, measure the calculated width / height of the element, then add them back and measure again. Then separate the new / old values. Not tried, but it might work. JQuery itself uses a similar approach for many dimensions; it even has the undocumented function $.swap() just for that.

PS: You use -o-transform -moz-transform and -ms-transform too, right?

+21
Apr 09 '11 at 9:40
source share

The simplest solution for determining the scale factor between a document and an element is the following:

 var element = document.querySelector('...'); var scaleX = element.getBoundingClientRect().width / element.offsetWidth; 

This works because getBoundingClientRect returns the actual dimension, and offsetWidth / Height returns the size without scaling.

+49
Nov 12 '14 at 18:11
source share

If you need to target only web kit (because it is for iPhone or iPad), the most reliable and fastest way is to use your own javascript web resource:

 node = $("#yourid")[0]; var curTransform = new WebKitCSSMatrix(window.getComputedStyle(node).webkitTransform); alert(curTransform.a); // curTransform is an object, alert(curTransform.d); // a through f represent all values of the transformation matrix 

Here you can see the demo: http://jsfiddle.net/umZHA/

+7
Apr 10 2018-11-11T00:
source share

Too late for the OP, but may be useful in the future. There is an easy way to do this with splitting:

 function getTransformValue(element,property){ var values = element[0].style.webkitTransform.split(")"); for (var key in values){ var val = values[key]; var prop = val.split("("); if (prop[0].trim() == property) return prop[1]; } return false; } 

This is specific web code, but it can be easily extended to more browsers that change the first line.

+1
Jun 19 '13 at 10:01
source share



All Articles