2010-06-19 63 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