2010-07-26 103 views
7

我正在使用拖放的html5界面。当我拖动一个元素时,目标会获得一个css类,这使得它由于-webkit动画而双向旋转。转换CSS3动画:旋转。获取旋转元件当前角度的方法?

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

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

由于到目前为止 亨德里克

+0

此答案适用于CSS3 3DTransforms:http://stackoverflow.com/a/18658090/139361 – Dan 2013-09-06 12:46:17

+0

关于3D矩阵的数学答案可以在这里找到:http://math.stackexchange.com/questions/489298/inverse -3d-transforms-from-matrix-given-end-formula-needed – Dan 2013-09-10 09:33:56

回答

18

我最近不得不写一个功能,完全按照你的要求!随意使用它:

// 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轴旋转)。

+1

必须改变这一行才能使用较新的浏览器: var a = parseFloat(splits [0] .substr(9)); – Orwellophile 2013-06-20 12:05:08

+0

谢谢你让我知道。这是3D变换的一个问题,我只是更新了代码以使用2d和3d变换。 – lakenen 2013-06-20 18:30:32

4

window.getComputedStyle(元件,NULL)[ ' - WebKit的变换']将返回一个表示当前变换矩阵的字符串。 您可以首先解析该字符串,然后对其应用一些数学运算,从而计算出它的旋转度。