HTML - DOM樣式物件animation屬性



animation 屬性用於定義我們所需的樣式。我們可以使用 animation 關鍵字組合 animation-name、animation-duration、animation-iteration-count 等屬性。

語法

以下是獲取或設定屬性的語法。

設定屬性
object.style.animation="name duration timingFunction delay iterationCount direction fillMode playState";
獲取屬性
object.style.animation;

屬性值

此屬性接受以下列出的值。

描述
animationName 它指定附加到選擇器的關鍵幀的名稱。其預設值為none
animationDuration 它指定動畫的時間長度。其預設值為0
animationTimingFunction 它指定動畫的速度。其預設值為ease
animationDelay 它指定動畫開始之前的延遲。其預設值為0
animationIterationCount 它指定動畫重複的次數。其預設值為1
animationDirection 它指定動畫是否應該在交替迴圈中反向播放。其預設值為normal
animationFillMode 它指定動畫結束時要應用的值。其預設值為none
animationPlayState 它指定動畫是正在執行還是暫停。其預設值為running

返回值

它返回一個字串值,表示元素的 animation 屬性。

HTML DOM 樣式物件“animation”屬性的示例

以下示例說明了 animation 屬性。

更改 div 元素的動畫

在下面的示例中,我們將 div 元素的移動方向從(從左到右)更改為(從上到下)。

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Style Object animation Property</title>
    <style>
        #animation {
            width: 100px;
            height: 100px;
            background: #04af2f;
            position: relative;
            animation: right 3s infinite;
        }
        @keyframes right {
            from {
                left: 0px;
            }
            to {
                left: 400px;
            }
        }
        @keyframes down {
            from {
                top: 0px;
            }
            to {
                top: 400px;
            }
        }
    </style>
</head>
<body>
    <p>Click to change the direction of animation.</p>
    <button onclick="fun()">Animate</button>
    <div id="animation"></div>
    <script>
        function fun() {
            document.getElementById("animation").style.animation = "down 5s 3";
        }
    </script>
</body>
</html>

帶有延遲和大小變化的動畫

在下面的示例中,我們對 div 容器進行了動畫處理,使其形狀和顏色發生變化,並延遲 2 秒。

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM Style Object animation Property</title>
    <style>
        #animation {
            width: 100px;
            height: 100px;
            background: #04af2f;
            position: relative;
            animation: right 3s infinite;
        }
        @keyframes right {
            from {
                left: 0px;
            }
            to {
                left: 400px;
            }
        }
        @keyframes down {
            from {
                top: 0px;
                width: 100px;
                height: 100px;
            }
            to {
                top: 400px;
                width: 200px;
                height: 200px;
                background: yellow
            }
        }
    </style>
</head>
<body>
    <p>Click to change the direction of animation.</p>
    <button onclick="fun()">Animate</button>
    <div id="animation"></div>
    <script>
        function fun() {
            document.getElementById("animation").style.animation = "down 5s 3 2s";
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
animation 支援 43 支援 12 支援 16 支援 9 支援 30
html_dom_style_object_reference.htm
廣告