Get the value of -webkit-transform of an element with jquery

后端 未结 6 473
终归单人心
终归单人心 2020-11-29 22:35

I\'m manipulating a div with the new cool css3 way of doing a transform like this:

$(\"#thediv\").css(\"-webkit-transform\",\"translate(-770px, 0px)\");
         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 23:14

    The reason you get the matrix string value, is that jQuery's css function is obtaining the computed style (the result of window.getComputedStyle($("#thediv")[0]).webkitTransform).

    To get the actual string value which you set it to in the previous call ("translate(-770px, 0px)") you can use:

    var t = $("#thediv")[0].style.webkitTransform;
    

    From that you could just use string methods to get the x value, e.g:

    t.substring(t.indexOf("(") + 1, t.indexOf(",") - 2)
    

    which gives -770. However, note that this is only acceptable if you know that the value exists and is in the form you're using (with just a translate(xpx, ypx), since other values are valid!

    If you'd prefer to use the computed style, then (to add to @Maz's suggestion), to get the 5th value (the x transform), you can do:

    new WebKitCSSMatrix($("#thediv").css("-webkit-transform")).e;
    

    To get the sixth one (the y transform) you use the f property of the matrix.

提交回复
热议问题