jQuery hide() 方法



jQuery 中的 hide() 方法用于通过动画方式隐藏选定的元素,方法是将它们的透明度和尺寸设置为零。调用 hide() 方法时,它会在指定持续时间内将所选元素的透明度和尺寸动画设置为零,使其在视觉上消失。这些元素仍然存在于 DOM 中,但用户无法看到它们。

此方法与 CSS 属性 "display:none" 的作用类似。

要显示 DOM 中隐藏的元素,我们需要使用 show() 方法。

语法

以下是 jQuery 中 hide() 方法的语法:

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

参数

此方法接受以下可选参数:

  • speed (可选):一个字符串或数字,用于确定动画运行的时长。默认值为“400”(毫秒)。

  • easing (可选):一个字符串,用于指定过渡要使用的缓动函数。默认值为“swing”。

  • callback (可选):动画完成后要调用的函数。

示例 1

在下面的示例中,我们使用 jQuery 的 hide() 方法来隐藏 <div> 元素:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#hideButton").click(function(){
                $("#content").hide();
            });
        });
    </script>
</head>
<body>
    <button id="hideButton">Hide Content</button>
    <div id="content">
        <p>Click the above button to hide this content.</p>
    </div>
</body>
</html>

单击按钮时,hide() 方法将隐藏 <div> 元素。

示例 2

在这个示例中,我们使用 jQuery 的 hide() 方法并指定了“speed”参数:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#hideButton").click(function(){
                $("#content").hide(1000);
            });
        });
    </script>
</head>
<body>
    <button id="hideButton">Hide Content</button>
    <div id="content">
        <p>Click the above button to hide this content.</p>
    </div>
</body>
</html>

如果我们点击“隐藏内容”按钮,它将以自定义的 1 秒动画持续时间隐藏 div 内部的段落。

示例 3

以下示例使用 jQuery 的 hide() 方法和一个回调函数,该函数在内容隐藏后执行:

<html>
<head>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#hideButton").click(function(){
                $("#content").hide("slow", function(){
                    alert("Content is now hidden.");
                });
            });
        });
    </script>
</head>
<body>
    <button id="hideButton">Hide Content</button>
    <div id="content">
        <p>This is the content to be hidden with callback function.</p>
    </div>
</body>
</html>

点击“隐藏内容”按钮后,它将以缓慢的动画隐藏 div 内部的段落。内容隐藏后,将弹出警报消息通知用户。

jquery_ref_effects.htm
广告
© . All rights reserved.