2010-12-05 48 views
7

我真的陷入困境。我想创建一个CSS动画(下面)来激活点击div。我认为我能做到的唯一方法就是使用javascript创建一个onClick事件。不过,我不知道如何运行/ refrence在我的CSS文件中的动画。谁能帮我?如何使用javascript激活CSS3(webkit)动画?

这是我的css文件中的动画,我想通过单击div来运行。

@-webkit-keyframes colorchange { 
0% { 
    background-color: red; 
    opacity: 1.0; 
    -webkit-transform: scale(1.0) rotate(0deg); 
} 
33% { 
    background-color: blue; 
    opacity: 0.75; 
    -webkit-transform: scale(1.1) rotate(-5deg); 
} 
67% { 
    background-color: green; 
    opacity: 0.5; 
    -webkit-transform: scale(1.1) rotate(5deg); 
} 
100% { 
    background-color: red; 
    opacity: 1.0; 
    -webkit-transform: scale(1.0) rotate(0deg); 
} 
} 

我甚至尝试把CSS在同一文件中的JavaScript(的index.html),并用下面的代码,试图激活它的点击,但没有运气。

<script> 
function colorchange(test) 
{ 
test.style.webkitAnimationName = 'colorchange '; 
} 
</script> 

请帮助:)

回答

11

你错过了时间,你必须在名称尾随空间分配:

function colorchange(test) 
{ 
    test.style.webkitAnimationName = 'colorchange'; // you had a trailing space here which does NOT get trimmed 
    test.style.webkitAnimationDuration = '4s'; 
} 

一些更多的相关信息在@-webkit-keyframes
http://webkit.org/blog/324/css-animation-2/

更新

一些工作代码。

<html> 
    <head> 
    <style> 
    @-webkit-keyframes colorchange { 
    0% { 
     background-color: red; 
     opacity: 1.0; 
     -webkit-transform: scale(1.0) rotate(0deg); 
    } 
    33% { 
     background-color: blue; 
     opacity: 0.75; 
     -webkit-transform: scale(1.1) rotate(-5deg); 
    } 
    67% { 
     background-color: green; 
     opacity: 0.5; 
     -webkit-transform: scale(1.1) rotate(5deg); 
    } 
    100% { 
     background-color: red; 
     opacity: 1.0; 
     -webkit-transform: scale(1.0) rotate(0deg); 
    } 
    } 
    </style> 

    <script> 
    function colorchange(e) { 
     if (e.style.webkitAnimationName !== 'colorchange') { 
      e.style.webkitAnimationName = 'colorchange'; 
      e.style.webkitAnimationDuration = '4s'; 

      // make sure to reset the name after 4 seconds, otherwise another call to colorchange wont have any effect 
      setTimeout(function() { 
       e.style.webkitAnimationName = ''; 
      }, 4000); 
     } 
    } 
    </script> 
    </head> 

    <body> 
     <div onclick="colorchange(this)">Hello World!</div> 
    </body> 
</html> 
+0

谢谢你,我没有看到尾随空间。但我仍然有这个问题。如果我这样做,例如:test.style.height =“50px”;它会动画和工作,但是如果我尝试调用我已经预先定义的自定义动画,请执行以下操作:test.style.webkitAnimationName ='colorchange';没有任何工作。有关于此的任何想法? – user531192 2010-12-05 14:06:34