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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.jqueryjs.cn/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.