2010-07-26 190 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的變換']將返回一個表示當前變換矩陣的字符串。 您可以首先解析該字符串,然後對其應用一些數學運算,從而計算出它的旋轉度。