Get translate3d values of a div?

前端 未结 6 722
难免孤独
难免孤独 2020-11-30 12:30

Say a div has this applied to it:

-webkit-transform: translate3d(0px, -200px, 0px)

How could I retrieve those values with jQuery?

6条回答
  •  春和景丽
    2020-11-30 13:24

    I don't know about the various edge cases, but in my case it's always 3 values like 'translate3d(23px, 34px, 40px)', so this was the cleanest way I could find:

    function getMatrix(element) {
        const values = element.style.transform.split(/\w+\(|\);?/);
        const transform = values[1].split(/,\s?/g).map(parseInt);
    
        return {
          x: transform[0],
          y: transform[1],
          z: transform[2]
        };
    }
    

    Result:

    {x: 238, y: 0, z: 0}
    

提交回复
热议问题