通過js獲取元素css3的transform rotate旋轉角度方法


我們再試用jquery獲取樣式的時候是通過$('domName').css('transform');的方式來獲取元素的css樣式,但是通過它獲取到的css3的transform屬性是以矩陣的方式呈現的:matrix(a, b, c, d, e, f);這樣的返回值並不是我們想要的結果。

我們要想獲取真正的旋轉角度值就需要通過一系列的處理來過去,具體方法是:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Document</title>
 7 </head>
 8 <style>
 9     #divTransform {
10         margin: 30px;
11         width: 200px;
12         height: 100px;
13         background-color: yellow;
14         /* Rotate div */
15         transform: rotate(9deg);
16         -ms-transform: rotate(9deg);
17         /* Internet Explorer */
18         -moz-transform: rotate(9deg);
19         /* Firefox */
20         -webkit-transform: rotate(9deg);
21         /* Safari 和 Chrome */
22         -o-transform: rotate(9deg);
23         /* Opera */
24     }
25 </style>
26 
27 <body>
28 <div id="divTransform">
29 </div>
30 </body>
31 <script>
32     var el = document.getElementById("divTransform");
33     var st = window.getComputedStyle(el, null);
34     var tr = st.getPropertyValue("-webkit-transform") ||
35         st.getPropertyValue("-moz-transform") ||
36         st.getPropertyValue("-ms-transform") ||
37         st.getPropertyValue("-o-transform") ||
38         st.getPropertyValue("transform") ||
39         "FAIL";
40     // With rotate(30deg)...
41     // matrix(0.866025, 0.5, -0.5, 0.866025, 0px, 0px)
42     console.log('Matrix: ' + tr);
43     // rotation matrix - http://en.wikipedia.org/wiki/Rotation_matrix
44     var values = tr.split('(')[1].split(')')[0].split(',');
45     var a = values[0];
46     var b = values[1];
47     var c = values[2];
48     var d = values[3];
49     var scale = Math.sqrt(a * a + b * b);
50     console.log('Scale: ' + scale);
51     // arc sin, convert from radians to degrees, round
52     var sin = b / scale;
53     // next line works for 30deg but not 130deg (returns 50);
54     // var angle = Math.round(Math.asin(sin) * (180/Math.PI));
55     var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
56     console.log('Rotate: ' + angle + 'deg');
57 </script>
58 
59 </html>
 

這個方法是國外的牛人寫的,記錄下來。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM