如何在 JavaScript 中读取/解析单个转换样式值? [英] How to read/parse individual transform style values in JavaScript?

查看:21
本文介绍了如何在 JavaScript 中读取/解析单个转换样式值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Webkit 去年关于 3D 变换的博文解释了各种变换 '可以在 -webkit-transform 属性中使用的函数.例如:

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:

#myDiv {
  -webkit-transform: scale(1.1) rotateY(7deg) translateZ(-1px);
}

我的问题:如何访问 JavaScript 中的单个值?当您读取元素的 webkitTransform 属性时,您只会得到一个包含 16 个值的 matrix3d() 函数,就像这样...

My question: how do you access individual values in JavaScript? When you read the webkitTransform property of the element, you just get a matrix3d() function with 16 values in it, like this...

matrix3d(0.958684, 0.000000, .....)

有没有办法只读取单个转换对象的值,例如rotateY()?还是我必须从 matrix3d() 字符串中读取它,以及如何读取?

Is there a way to just read the value of an individual transform thing, like rotateY()? Or do I have to read it from the matrix3d() string, and how?

推荐答案

// 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*/);
}

希望这有帮助!请注意,除了普通的 DOM API 和本机 Javascript RegExp 函数之外,我没有使用其他库.因此,这应该普遍适用于跨浏览器和应用程序.

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.

这篇关于如何在 JavaScript 中读取/解析单个转换样式值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆