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.jquery.com/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.jquery.com/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.jquery.com/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
廣告