【问题标题】:CSS3 animation on transform: rotate. Way to fetch current deg of the rotating element?变换上的 CSS3 动画:旋转。获取旋转元素当前度数的方法?
【发布时间】:2011-03-21 03:35:23
【问题描述】:

我正在开发一个使用拖放的 html5 界面。当我拖动一个元素时,目标获得了一个 css 类,这使得它由于 -webkit-animation 而双向旋转。

@-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'。

所以我的问题是:有没有办法获取通过动画旋转的元素的当前度值?

到目前为止谢谢 亨德里克

【问题讨论】:

标签: animation html drag-and-drop css transform


【解决方案1】:

window.getComputedStyle(element,null)['-webkit-transform'] 将返回一个表示当前变换矩阵的字符串。 您可以通过首先解析该字符串,然后对其进行一些数学运算来计算其旋转度数。

【讨论】:

    【解决方案2】:

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

    // 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;
    }
    

    希望这会有所帮助!

    编辑我更新了代码以使用 matrix3d 字符串,但它仍然只给出 2d 旋转度数(即围绕 Z 轴旋转)。

    【讨论】:

    • 必须更改此行以使用较新的浏览器:var a = parseFloat(splits[0].substr(9));
    • 感谢您告诉我。这是 3d 变换的问题,我刚刚更新了代码以同时使用 2d 和 3d 变换。
    猜你喜欢
    • 2011-07-24
    • 2015-10-19
    • 1970-01-01
    • 2013-05-22
    • 2014-02-02
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多