jQuery show()方法

栏目: jquery 发布时间:2024-12-24

show() 方法是 jQuery 提供的一个非常实用的动画方法,用于显示被隐藏的 HTML 元素。

基本用法

show() 方法默认会在 400 毫秒内以标准效果显示匹配的元素。你可以通过传递参数来自定义动画的速度和效果。

$(selector).show(speed, callback);
  • selector:选择你想要显示的元素,例如 $("#myDiv")$(".myClass")
  • speed(可选):动画的速度。可以是以下三种值之一:
    • "slow":600 毫秒。
    • "fast":200 毫秒。
    • 数字(毫秒):例如 400 表示 400 毫秒。
  • callback(可选):动画完成后执行的函数。

示例

  1. 基本显示
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery show() 方法</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#showButton").click(function(){
                $("#myDiv").show();
            });
        });
    </script>
    <style>
        #myDiv {
            display: none;
            width: 100px;
            height: 100px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
    <button id="showButton">显示 Div</button>
    <div id="myDiv"></div>
</body>
</html>

在这个示例中,当点击按钮时,隐藏的 div 元素会被显示出来。

  1. 自定义速度
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery show() 方法 - 自定义速度</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#showButton").click(function(){
                $("#myDiv").show(1000); // 1 秒内显示
            });
        });
    </script>
    <style>
        #myDiv {
            display: none;
            width: 100px;
            height: 100px;
            background-color: lightcoral;
        }
    </style>
</head>
<body>
    <button id="showButton">显示 Div</button>
    <div id="myDiv"></div>
</body>
</html>

在这个示例中,div 元素会在 1 秒内逐渐显示出来。

  1. 使用回调函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery show() 方法 - 回调函数</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#showButton").click(function(){
                $("#myDiv").show("slow", function() {
                    alert("动画完成!");
                });
            });
        });
    </script>
    <style>
        #myDiv {
            display: none;
            width: 100px;
            height: 100px;
            background-color: lightgreen;
        }
    </style>
</head>
<body>
    <button id="showButton">显示 Div</button>
    <div id="myDiv"></div>
</body>
</html>

在这个示例中,当 div 元素显示完成后,会弹出一个提示框显示“动画完成!”。

总结

show() 方法是 jQuery 提供的一个简单但强大的工具,用于显示隐藏的 HTML 元素。通过调整速度和回调函数,你可以轻松控制动画的行为,提升用户体验。希望这个教程能帮助你更好地理解和使用 show() 方法!

本文地址:https://www.tides.cn/p_jquery-show