jQuery fadeIn() 方法



淡入效果是一種視覺過渡,其中元素從最初隱藏或透明逐漸變得更可見。它在指定持續時間內平滑地增加元素的不透明度,從而建立平滑的過渡。

fadeIn() 方法用於在 jQuery 中透過淡入使隱藏的元素可見。它將所選元素的不透明度從 0 動畫到 1,使其可見。

此方法也可以與 "fadeOut()" 方法一起使用。

語法

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

$(selector).fadeIn(speed,easing,callback)

引數

此方法接受以下可選引數:

  • speed(可選):一個字串或數字,確定動畫執行多長時間。它可以取“slow”、“fast”等值,或以毫秒為單位的特定持續時間(例如,1000 表示 1 秒)。

  • easing(可選):一個字串,指定用於動畫的緩動函式(例如,“swing”或“linear”)。

  • callback(可選):動畫完成後要呼叫的函式。它對每個選定的元素執行。

示例 1

在以下示例中,我們使用 JavaScript fadeIn() 方法為 <div> 元素新增“緩慢”淡入效果:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $("#fadeButton").click(function() {
        $("#content").fadeIn("slow");
    });
});
</script>
</head>
<body>

<button id="fadeButton">Click me!</button>
<div id="content" style="display: none;">
    <h2>Welcome to Tutorialspoint</h2>
    <p>This text will fade in when the button is clicked.</p>
</div>
</body>
</html>

如果我們點選按鈕,<div> 元素將淡入。

示例 2

在此示例中,<div> 元素在頁面載入時自動淡入:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $("#content").fadeIn("slow");
});
</script>
</head>
<body>

<div id="content" style="display: none;">
    <h2>Welcome to Tutorialspoint!</h2>
    <p>This content fades in automatically when the page loads.</p>
</div>
</body>
</html>

如果我們執行上述程式,<div> 元素的內容將自動淡入。

示例 3

以下示例依次淡入多個元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $("#fadeButton").click(function() {
        $(".content").each(function(index) {
            $(this).delay(500 * index).fadeIn("slow");
        });
    });
});
</script>
</head>
<body>

<button id="fadeButton">Click me!</button>
<div class="content" style="display: none;">
    <h2>First Element</h2>
</div>
<div class="content" style="display: none;">
    <h2>Second Element</h2>
</div>
<div class="content" style="display: none;">
    <h2>Third Element</h2>
</div>
</body>
</html>

如果我們點選按鈕,所有三個 <div> 元素將淡入。

示例 4

在下面的示例中,我們一起使用 fadeIn() 和 fadeOut() 方法來建立一個簡單的切換效果:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $("#toggleButton").click(function() {
        $("#content").fadeOut("slow", function() {
            // Fade out complete callback
            $("#content").fadeIn("slow");
        });
    });
});
</script>
</head>
<body>

<button id="toggleButton">Click me!</button>
<div id="content">
    <h2>Welcome to Tutorialspoint!</h2>
</div>
</body>
</html>

當點選按鈕時,<div> 元素將淡出,然後淡入。

jquery_ref_effects.htm
廣告

© . All rights reserved.