2010-12-05 8 views
7

本当につまらない。私が作成したCSSアニメーション(下記)をdivをクリックすると有効にしたい。私がそれを行うことができると思った唯一の方法は、javascriptを使ってonClickイベントを作成することでした。しかし、私は/ refrenceを実行する方法を知っていない私のCSSファイルにあるアニメーション。誰でも助けてくれますか?javascriptを使用してCSS3(Webkit)アニメーションをアクティブにするには?

これはdivをクリックして実行したい私のCSSファイルのアニメーションです。

@-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); 
} 
} 

は私もジャバスクリプト(index.htmlの)と同じファイルにCSSを入れて試してみてくださいとクリックで、それをアクティブにするには、次のコードを使用しますが、運。

<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

+0

期間を設定しましたか?それなしでは動作しません。上のCSSを使ってローカルでテストしたところ、うまくいきました。 –

+0

ええ、私は期間を持っており、アニメーションはうまく動作します。しかし、私はそれを再生するためにjavascript onclickを使ってみるとうまくいきません。 (onclickが動作します)。あなたはそれをonclickで作業させましたか? – user531192

関連する問題