使用jquery直接获取转换的css值 [英] Fetch the css value of transform directly using jquery
问题描述
我正在通过element.style[vendor + 'Transform']
从dom中获得-moz-transform: translate(-283.589px, 0px)
.现在,我想提取值-283.589px
以便在我的应用程序中使用它,但没有获取确切的方法来获取它.如果我做console.log($('.slide').css("-moz-transform"))
,它将返回矩阵值作为matrix(1, 0, 0, 1, -283.589px, 0px)
. jquery中是否有合适的方法直接获取值-283.589px
.我不想做任何矩阵计算.
I am getting -moz-transform: translate(-283.589px, 0px)
from dom by doing element.style[vendor + 'Transform']
. Now i want to extract the value -283.589px
to use it in my application but not getting the exact way to fetch it. If i do console.log($('.slide').css("-moz-transform"))
it returns the matrix value as matrix(1, 0, 0, 1, -283.589px, 0px)
. Is there a suitable way in jquery to directly fetch the value -283.589px
. I dont want to do any matrix calculation.
推荐答案
我有好消息和坏消息.
我将从一个坏消息开始:在检查了jQuery返回的对象之后,matrix
对象只不过是一个字符串,除了字符串以外,您绝对不可能获得另一个对象.我们非常想不同意它不应该是字符串:CSS值是字符串,因此jQuery返回字符串.
I'll start with the bad news: After examining the object that jQuery returns, the matrix
object is nothing but a string and there's absolutely no way you can get another object but a string. As much we would like to disagree that it shouldn't be a string: CSS values are strings, hence jQuery returns strings.
因此,无论您是否喜欢,您实际上都必须解析字符串以获取值.好消息是:我有两个解决方案.
So, whether you like it or not, you really have to parse the string in order to get the value. The good news is: I've got two solutions.
现在,如果您非常确定前两个值始终相同,则可以简单地使用子字符串.但是,下一个问题是:在Google Chrome浏览器中,值-283.589px
被更改为-283.5889892578125
.
Now, if you're VERY sure that the first couple of values are ALWAYS the same you could simply use substring. But, next problem: in Google Chrome, the value -283.589px
is being changed to -283.5889892578125
.
老实说,您需要一个更高级的字符串解析器来获取正确的值.我欢迎使用正则表达式:
Honestly, you need a more advanced string parser to get the correct value. I welcome regular expression:
var matrix = $('.selector').css('-moz-transform');
var values = matrix.match(/-?[\d\.]+/g);
这将获取字符串的所有值.
This gets all the values of your string.
通过选择正确的索引,您可以获得价值:
By selecting the right index, you can get your value:
var x = values[5];
那是我能提供的最好的解决方案,我很肯定这是唯一可能的解决方案.
That's the best solution I can provide and I'm positive it's the only possible solution.
这篇关于使用jquery直接获取转换的css值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!