jQuery show() 方法



jQuery 中的 show() 方法用於透過動畫顯示隱藏元素,使其可見。它用於顯示那些使用 jQuery 的 hide() 方法或 CSS 屬性隱藏的元素。

如果元素已經可見,則 show() 方法對其沒有任何影響。可以使用 duration、easing 和回撥函式等選項自定義動畫。

要隱藏 DOM 上的元素,我們需要使用 hide() 方法。

語法

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

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

引數

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

  • speed (可選):一個字串或數字,確定動畫執行的時長。預設值為 400 毫秒。可能的值為:毫秒數、slow、fast。

  • easing (可選):一個字串,指示要用於過渡的緩動函式。預設值為 "swing"。可能的值為:swing、linear。

  • callback (可選):動畫完成後要呼叫的函式。

示例 1

在下面的示例中,我們使用 jQuery 的 show() 方法來顯示隱藏的 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#hiddenElement").show();
    });
});
</script>
</head>
<body>
<button id="showBtn">Show Element</button>
<div id="hiddenElement" style="display:none;">
    <h3>This is a hidden element. It will be shown when the button is clicked.</h3>
</div>
</body>
</html>

單擊按鈕時,show() 方法會顯示隱藏的 <div> 元素。

示例 2

下面的示例在頁面載入時顯示兩個隱藏的元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $(".hidden").show();
});
</script>
</head>
<body>
<div class="hidden" style="display:none;">
    <h3>Hidden element 1</h3>
</div>
<div class="hidden" style="display:none;">
    <h3>Hidden element 2</h3>
</div>
</body>
</html>

執行上述程式後,它將 id 為 hidden 的隱藏 <div> 元素顯示到 DOM 上。

示例 3

下面的示例顯示帶有動畫的隱藏元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#hiddenElement").show("slow");
    });
});
</script>
</head>
<body>
<button id="showBtn">Show Element with Animation</button>
<div id="hiddenElement" style="display:none;">
    <h3>This is a hidden element. It will be shown with animation when the button is clicked.</h3>
</div>
</body>
</html>

單擊“顯示帶動畫的元素”按鈕後,它會觸發一個平滑的動畫,顯示隱藏的元素。

jquery_ref_effects.htm
廣告