jQuery 事件 toggle() 方法



jQuery 事件toggle() 方法用於切換所選元素的可見性,並在 1 秒內(預設)自動在 .hide().show() 方法之間切換。

此方法接受一個可選引數,您可以使用它來處理切換速度(隱藏或顯示效果),只需根據該引數的值傳遞 'speed' 引數,它就會處理切換速度。

語法

以下是 jQuery 事件toggle() 方法的語法:

$(selector).toggle(speed, easing, callback);

引數

此方法接受三個引數 'speed'、'easing' 和 'callback',如下所述:

  • speed - 指定隱藏或顯示效果的速度(值:毫秒、'slow'、'fast')。
  • easing - 指定過渡的緩動函式(預設為 'swing')。
  • callback - 在切換效果完成後執行的函式。

返回值

此方法沒有任何返回值。

示例 1

以下是 jQuery 事件 toggle() 方法的基本示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <div class="">Toggle event occured</div>
    <script>
        $('div').toggle(function(){
            alert("Toggle event triggered");
        });
    </script>
</body>
</html>

輸出

以上程式顯示一條訊息,並在切換事件觸發時自動隱藏,並在瀏覽器螢幕上彈出一個警報視窗:


示例 2

使用名為 'speed' 的可選引數來處理切換效果的速度:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 200px;
        padding: 10px;
        background-color: green;
        color: white;
        border-radius: 10px;
    }
</style>
</head>
<body>
    <div class="">Toggle event occured</div>
    <span></span>
    <script>
        $('div').toggle(3000, function(){
            $('span').text("Hidden");
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示一條帶有綠色背景的訊息。然後它將自動開始隱藏,並在 3 秒內完全隱藏:


示例 3

讓我們使用 "slow" 和 "fast" 值與 speed 一起檢視切換效果:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 200px;
        padding: 10px;
        background-color: green;
        color: white;
        border-radius: 10px;
    }
    .fst{
        width: 200px;
        padding: 10px;
        background-color: red;
        color: white;
        border-radius: 10px;
    }
</style>
</head>
<body>
    <p>Slow value example</p>
    <div class="slw">Toggle event occured(with slow value)</div>
    <p>Fast value example</p>
    <div class="fst">Toggle event occured(with slow value)</div>
    <span></span>
    <script>
        $('.slw').toggle((5000, "slow"), function(){
            $('span').text("Hidden");
        });
        $('.fst').toggle((5000, "fast"), function(){
            $('span').text("Hidden");
        });
    </script>
</body>
</html>

輸出

執行上述程式後,將顯示兩個帶有綠色和紅色背景的 div 元素。第一個 div 將在 5 秒內以緩慢效果隱藏,第二個 div 將在 5 秒內以快速效果隱藏:


jquery_ref_events.htm
廣告