代码之家  ›  专栏  ›  技术社区  ›  larrydahooster

CSS3变换动画:旋转。如何获取旋转元件的当前度数?

  •  7
  • larrydahooster  · 技术社区  · 14 年前

    我正在开发一个使用拖放的html5接口。当我拖动一个元素时,目标得到一个css类,由于-webkit动画,它可以双向旋转。

    @-webkit-keyframes pulse {
       0%   { -webkit-transform: rotate(0deg);  }
       25%  { -webkit-transform:rotate(-10deg); }
       75%  { -webkit-transform: rotate(10deg); }
       100% { -webkit-transform: rotate(0deg);  }
      }
    
    .drag
    {
        -webkit-animation-name: pulse;
        -webkit-animation-duration: 1s;
        -webkit-animation-iteration-count: infinite;
        -webkit-animation-timing-function: ease-in-out;
    }
    

    我的第一个想法是用jquery和.css('-webkit transform')方法检查css属性。但是这个方法只返回“none”。

    所以我的问题是:有没有一种方法可以得到通过动画旋转的元素的当前度数值?

    非常感谢

    2 回复  |  直到 14 年前
        1
  •  20
  •   lakenen    11 年前

    我最近不得不写一个函数,它完全符合你的要求!请随意使用:

    // Parameter element should be a DOM Element object.
    // Returns the rotation of the element in degrees.
    function getRotationDegrees(element) {
        // get the computed style object for the element
        var style = window.getComputedStyle(element);
        // this string will be in the form 'matrix(a, b, c, d, tx, ty)'
        var transformString = style['-webkit-transform']
                           || style['-moz-transform']
                           || style['transform'] ;
        if (!transformString || transformString == 'none')
            return 0;
        var splits = transformString.split(',');
        // parse the string to get a and b
        var parenLoc = splits[0].indexOf('(');
        var a = parseFloat(splits[0].substr(parenLoc+1));
        var b = parseFloat(splits[1]);
        // doing atan2 on b, a will give you the angle in radians
        var rad = Math.atan2(b, a);
        var deg = 180 * rad / Math.PI;
        // instead of having values from -180 to 180, get 0 to 360
        if (deg < 0) deg += 360;
        return deg;
    }
    

    希望这有帮助!

    编辑

        2
  •  4
  •   Keigo Imai    14 年前

    getComputedStyle(element,null)['-webkit transform']将返回表示当前转换矩阵的字符串。

    推荐文章