从字符串中获取x和y值:' matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,3,3,1,1)'

时间:2015-07-27 16:06:17

标签: javascript jquery

我尝试根据指定pos 'x''y'这样的<{p}}来创建一个返回x或y元素的函数转换

function getTranslate(el, pos) {
    var translate = '',
        position = 0;

    if(el.css('transform')) {
        translate = el.css('transform');
    }
    else if(el.css('-webkit-transform')) {
        translate = el.css('-webkit-transform');
    } else {
        translate = 'translate3d(0, 0, 0)';
    }

    if(pos == 'x') {
        position = /* Get x position here */ ;
    }
    else if(pos == 'y') {
        position = /* Get y position here */ ;
    }
}

当我们获取转换属性时,会为'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 3, 3, 3, 1)'返回translate3d(3px, 3px, 0)more info here)之类的字符串。这将存储在我需要解析的translate变量中,以便让position变量根据给予函数的内容只存储x或y位置的数值。我无法弄清楚如何解析该字符串

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式解析翻译字符串:

var regex = /translate3d\(\s*([^ ,]+)\s*,\s*([^ ,]+)\s*,\s*([^ )]+)\s*\)/;
var test = "translate3d( 10px,20px , 30px)"
var result = test.split(regex);
alert('x is '+result[1]+",  and y is "+result[2]);

答案 1 :(得分:0)

您可以使用.offset()或.position()获取元素的位置。

它们是相对于文档的第一个获取位置,第二个是相对于偏移父级的位置。

position = element.offset();
position = element.position();

http://api.jquery.com/offset/

https://api.jquery.com/position/

相关问题