2010-06-19 88 views
2

我想通過javascript/css3旋轉一個盒子,每次點擊它時都會旋轉。它的工作原理,但只是第一次點擊它。每次之後,我都會收到警報,這意味着它不是javascript錯誤 - 但不包含動畫。css3動畫只發生一次

這是我簡單的頁面 -

<script> 
    function rotate(box) 
    { 
    alert('start'); 
    box.style.webkitTransform = 'rotate(360deg)'; 
    } 
</script> 

<style> 
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; } 
</style> 

<div id='box' onclick='rotate(this);'></div> 

我想需要有一些我需要的旋轉()告訴它返回到開始階段,以便它可以再次旋轉360後放。

回答

1

我重複使用了之前製作的腳本。它現在應該也支持Mozilla。

<!-- head part --> 
<script type="text/javascript"> 
var angle = 0; //Current rotation angle 
var nbSteps = 30; //More steps is more fluid 
var speed = 1000; //Time to make one rotation (ms) 
var count = 0; //Count the nb of movement (0..nbSteps-1) 
var element = null; 

/** 
* Rotate the element passed 
*/ 
function rotate(box) { 
    if(count == 0) { 
     element = box; 
     rotateLoop(); 
    } 
} 

/** 
* Recursive method that rotate step by step 
*/ 
function rotateLoop() { 
    angle-=360/nbSteps; 

    setElementAngle(angle); 
    count++; 

    if(count < nbSteps) { 
     setTimeout("rotateLoop()",speed/nbSteps); 
    } 
    else { 
     count=0; 
     setElementAngle(0); //Just to be sure 
    } 
} 

/** 
* Use for the rotation 
*/ 
function setElementAngle(angle) { 
    var rotationStyle = "rotate(" + (360-angle) + "deg)"; 
    element.style.WebkitTransform = rotationStyle; 
    element.style.MozTransform = rotationStyle; 
    element.style.OTransform = rotationStyle; 
} 
</script> 

<style> 
#box{ 
    height:100px; 
    width:100px; 
    border:1px solid red; 
    } 
</style> 

<!-- body part --> 
<div id='box' onclick="rotate(this);"></div> 
1

編輯:假設你希望它是完全CSS:

Webkit的轉變,目前正在測試,非常粗糙。特別是對於你想要做的事情。由於這些都是「轉型」,而風格字符串非常複雜,所以會產生一個令人討厭的挑戰。

最好的事情做反向旋轉每隔點擊:

<script> 
function rotate(box) 
{ 
    box.style.webkitTransform = box.style.webkitTransform == "rotate(360deg)" ? "rotate(0deg)" : "rotate(360deg)"; 
} 
</script> 

<style> 
#box{ height:100px; width:100px; border:1px solid red; -webkit-transition: -webkit-transform 1s ease-out; } 
</style> 

<div id='box' onclick='rotate(this);'></div> 

或者你會不得不面對很多危險的編碼,或JavaScript的替代品。

+0

該解決方案將在第二次旋轉對面的方形。 我會用MozTransform屬性添加對Mozilla的支持,也許會添加一個額外的變量以避免已經處於輪換狀態的點擊事件。 – h3xStream 2010-06-22 00:13:30