簡體   English   中英

如何使用javascript激活CSS3(webkit)動畫?

[英]How to activate a CSS3 (webkit) animation using javascript?

我真的卡住了。 我想要一個我創建的CSS動畫(下面)來點擊一個div激活。 我認為我能做到的唯一方法是使用javascript創建onClick事件。 但是我不知道如何運行/參考我的css文件中的動畫。 誰能幫我?

這是我想通過單擊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);
 }
}

我甚至嘗試將css放在與javascript(index.html)相同的文件中,並使用以下代碼嘗試在點擊時激活它,但沒有運氣。

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

請幫忙 :)

您錯過了持續時間,並且您指定的名稱中有一個尾隨空格:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM