编程语言
首页 > 编程语言> > javascript – 如何将CSS转换矩阵转换回其组件属性

javascript – 如何将CSS转换矩阵转换回其组件属性

作者:互联网

我通过使用getComputedStyle()方法获得了元素的CSS变换矩阵,如下所示.

var style = window.getComputedStyle(elem1, null);
var trans = style.transform;

trans = matrix(1, 0, 0, 1, 1320, 290)

有没有办法重新计算变换矩阵以获得原始CSS规则,即.要转换,旋转,倾斜属性的值.我假设它可以通过反转用于形成矩阵的方法来计算.
附: – 转换属性的值以百分比给出,我想从矩阵中反算出这些百分比值.

CSS转换 – 转换:转换(200%,500%);

解决方法:

是的,有可能做到这一点!

矩阵的参数按此顺序排列:
矩阵(将scaleX(),skewY(),如果skewX(),的scaleY(),平移X(),平移Y())

阅读更多关于它here

如果要从该字符串中检索数字(矩阵(1,0,0,1,720,290),您可以使用此正则表达式:

style = window.getComputedStyle(elem1, null);
trans = style.transform;
numberPattern = /\d+/g;

values = trans.match( numberPattern );

这将返回以下数组:

["1", "0", "0", "1", "720", "290"]

评论后编辑

window.getComputedStyle中返回的值是计算值(即您使用的百分比被解析为像素值).您可以反转该计算,但您需要知道百分比用于确定应该有多少像素.

Enter CSS3 Transforms

One interesting thing about CSS transforms is that, when applying them with percentage values, they base that value on the dimensions of the element which they are being implemented on, as opposed to properties like top, right, bottom, left, margin, and padding, which only use the parent’s dimensions (or in case of absolute positioning, which uses its closest relative parent).
07001

如果您使用以下计算,您应该能够获得您使用的百分比:

style = window.getComputedStyle(elem1, null);
trans = style.transform;
numberPattern = /\d+/g;

values = trans.match( numberPattern );

computedTranslateX = values[4];
computedTranslatey = values[5];

xPercentage = (computedTranslateX / elem1.offsetWidth) * 100;
yPercentage = (computedTranslateY / elem1.offsetHeight) * 100;

小数点评后编辑

您可以使用不同的正则表达式来包含小数.

numberPattern = /\d+\.?\d+|\d+/g;

标签:javascript,css,css3,css-transforms,html
来源: https://codeday.me/bug/20190527/1164365.html