CSS3動畫的回調處理

咱們在作js動畫的時候,不少時候都須要作回調處理,如在一個動畫完成後觸發一個事件、一個動畫完成後執行另一個動畫等等,但在使用CSS3動畫時能不能捕獲到運動的狀態作回調處理呢?css

CSS3動畫也是能夠作回調處理的,這裏分爲兩個屬性,一個是transition[w3c文檔],另一個是animation[w3c文檔]html

一、transitioncss3

對於transition,能夠監聽transitionend事件,當動畫完成時觸發,能夠這樣使用:web

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>css3-transitionend - BeyondWeb</title>
    <style>
        * {margin: 0; padding: 0;}
        .rect {
            width: 100px;
            height: 100px;
            background-color: #f80;
            -webkit-transition: all .5s;
        }
    </style>
    <script>
        window.onload = function () {
            var _rect = document.querySelector('.rect');
            _rect.onclick = function () {
                _rect.style.webkitTransform = 'translateX(300px)';
            }

            _rect.addEventListener('webkitTransitionEnd', function () {
                alert('動畫執行完畢!');
                // callback here
            }, false);
        }
    </script>
</head>
<body>
    <div class="rect"></div>
</body>
</html>

二、animation動畫

對於animation咱們能夠監聽animationend事件,示例代碼以下:spa

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>css3-animationend - BeyondWeb</title>
    <style>
        * {margin: 0; padding: 0;}
        .rect {
            position: relative;
            width: 100px;
            height: 100px;
            background-color: #f80;
        }

        @-webkit-keyframes move {
            from {
                -webkit-transform: rotate(0);
            }
            to {
                -webkit-transform: rotate(360deg);
            }
        }
    </style>
    <script>
        window.onload = function () {
            var _rect = document.querySelector('.rect');
            _rect.onclick = function () {
                _rect.style.webkitAnimation = 'move 3s';
            }

            _rect.addEventListener('webkitAnimationEnd', function () {
                alert('動畫執行完畢!');
                // callback here
            }, false);
        }
    </script>
</head>
<body>
    <div class="rect"></div>
</body>
</html>

以上就是關於CSS3動畫回調處理的一些內容,最近在作H5頁面時用到了,總結一下。orm

相關文章
相關標籤/搜索