DIV CSS 佈局教程網

jQuery hover() 與 toggle() 用法指南:懸停與連續點擊的兩種切換
編輯:JQuery特效代碼     

jQuery 貼心地包裝了幾個「兩段式」互動:滑鼠移入/移出、鑰匙按下/放開,以及連續點擊的輪替。其中最常用到的就是 hover() 和 toggle()。

一、hover(over, out):滑鼠進出各跑一段

hover() 是對「滑鼠移到元素上、再移出」這個高頻操作的封裝,等於同時綁定 mouseenter 與 mouseleave。

參數:

  • over (Function):滑鼠移到元素上時要執行的函式。
  • out (Function):滑鼠移出元素時要執行的函式。
<script type="text/javascript">
$(function(){
    $("#panel h5.head").hover(function(){
        $(this).next().show();   // 懸浮時展開
    }, function(){
        $(this).next().hide();   // 移出時收起
    })
})
</script>

二、toggle(fn, fn):每次點擊輪流觸發

這個形式的 toggle 會切換要呼叫的函式:第一次點擊觸發第一個函式,再次點擊同一元素觸發第二個,之後無限輪替。若要移除,可用 unbind("click")。

<script type="text/javascript">
$(function(){
    $("#panel h5.head").toggle(function(){
        $(this).next().show();   // 第一次點擊
    }, function(){
        $(this).next().hide();   // 第二次點擊,之後不斷切換
    })
})
</script>

三、toggle() 無參數:切換可見狀態

不帶參數的 toggle() 是另一回事——它直接切換被選元素的顯示/隱藏。因此上面那段也可以簡化成:

<script type="text/javascript">
$(function(){
    $("#panel h5.head").toggle(function(){
        $(this).next().toggle();
    }, function(){
        $(this).next().toggle();
    })
})
</script>

甚至可以只寫:

$(function(){
    $("#panel h5.head").click(function(){
        $(this).next().toggle();
    })
})

可見 toggle(fn, fn) 只是「把兩段邏輯輪流執行」的機制,而 toggle() 是「反轉可見性」的動作,兩者名字相同但職責不同,別搞混。

四、加上樣式讓狀態更明顯

<style type="text/css">
.highlight{ background:#FF3300; }
</style>
<script type="text/javascript">
$(function(){
    $("#panel h5.head").toggle(function(){
        $(this).addClass("highlight");
        $(this).next().show();
    }, function(){
        $(this).removeClass("highlight");
        $(this).next().hide();
    });
})
</script>

這才是 toggle(fn, fn) 真正的價值所在:在兩個階段各自做「不一樣的事」。若兩段做的事完全相同,直接用 click 加 toggle() 就好。

版本提醒

toggle(fn, fn) 這種「事件切換」用法在 jQuery 1.9 之後已被移除,新專案請改用自行維護狀態的寫法,例如用一個 boolean 變數或 .toggleClass() 搭配 CSS 來控制。理解它的精神比記住 API 更重要。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved