jQuery animate() 方法



jQuery 中的 animate() 方法用於對選定的元素執行自定義動畫。它允許您在指定的時間內,並使用指定的緩動函式來動畫元素的 CSS 屬性,例如寬度、高度、不透明度等等。

jQuery 中的動畫只能運算元值,例如“margin: 30px”。像“background-color: red”這樣的字串值不能被動畫化,除非它們是像“show”、“hide”和“toggle”這樣的特定字串,它們控制動畫元素的可見性。

語法

以下是 jQuery 中 animate() 方法的語法:

(selector).animate({styles},speed,easing,callback)

引數

此方法接受以下引數

  • {styles}: 包含要動畫化的 CSS 屬性和值的 object 物件。

  • 注意:使用此 animate() 方法時,需要使用駝峰式命名法提供屬性名稱。例如,需要編寫 paddingRight 而不是 padding-right。

  • speed (可選): 動畫持續時間(毫秒)。預設值為 400 毫秒。

  • easing (可選): 指定元素在動畫不同點處的速度。預設為“swing”。

  • callback (可選): 動畫完成後要執行的函式。

示例 1

在下面的示例中,我們透過更改其寬度和高度來對元素“<div>”進行動畫處理,動畫時間為 1000 毫秒(1 秒):

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#animateBtn").click(function(){
        $("div").animate({
            width: "200px",
            height: "200px",
        }, 1000);
    });
});
</script>
</head>
<body>
<button id="animateBtn">Animate</button>
<div style="background-color: #40a944; 
   width: 100px; 
   height: 100px; 
   border-radius: 50%;">
</div>
</body>
</html>

單擊“動畫”按鈕後,<div> 元素將進行動畫。

示例 2

在下面的示例中,我們使用帶有回撥函式的 animate() 方法:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#animateBtn").click(function(){
        $("div").animate({
            width: "200px",
            height: "200px",
        }, 1000, "swing", function(){
            alert("Animation Completed!");
        });
    });
});
</script>
</head>
<body>
<button id="animateBtn">Click to Animate</button>
<div style="background-color: red; 
    width: 110px; 
    height: 100px;
    border-radius: 50%;">
</div>
</body>
</html>

當我們單擊按鈕時,<div> 元素的高度和寬度將在 1000 毫秒(1 秒)內進行動畫。動畫完成後,將顯示一條帶有“動畫完成!”訊息的警報。

另一種語法

以下是 JavaScript Effect animate() 方法的另一種語法:

(selector).animate({styles},{options})

引數

以下是此方法採用的引數

  • {styles}: 包含要動畫化的 CSS 屬性和值的 object 物件。

  • {options} (可選): 包含動畫附加選項的 object 物件。可能的值包括 duration、easing、complete、step、progress、queue、specialEasing、start、done、fail 和 always。還有一個在動畫完成後執行的回撥函式。

示例 3

在這裡,我們對 id 為“#box”的 <div> 元素使用 animate() 方法,使其寬度動畫化為 200 畫素,不透明度動畫化為 0.5,持續時間為 1000 毫秒(1 秒):

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
    #box {
        width: 60px;
        height: 50px;
        background-color: blue;
        margin: 50px;
    }
</style>
</head>
<body>
<!-- HTML element to be animated -->
<div id="box"></div>

<script>
$(document).ready(function(){
    // Animate the width and opacity of the element with id "box"
    $("#box").animate({
        width: "1100px",
        opacity: 0.5
    }, 1000); // Animation duration: 1000 milliseconds
});
</script>
</body>
</html>

執行上述程式後,<div> 元素將進行動畫。

jquery_ref_effects.htm
廣告
© . All rights reserved.