DIV CSS 佈局教程網

用 jQuery 實作鍵盤按鍵監聽的滑動切換效果
編輯:JQuery特效代碼     

這是一個靈感來自 NETTUTS 的實作,效果類似 Flash 般的滑動切換,相當吸睛。它的核心邏輯其實很簡單,主要用到 slideDown() 方法搭配鍵盤事件。

以 slideDown 顯示對應區塊

先定義兩個輔助函式:一個用來隱藏全部容器並滑動顯示指定元素,另一個則依連結的 href 決定要顯示哪個區塊。

// shows a given element and hides all others 
function showViaKeypress(element_id) 
{ 
    $(".container").css("display","none"); 
    $(element_id).slideDown("slow"); 
} 

// shows proper DIV depending on link 'href' 
function showViaLink(array) 
{ 
    array.each(function(i) 
    {    
        $(this).click(function() 
        { 
            var target = $(this).attr("href"); 
            $(".container").css("display","none"); 
            $(target).slideDown("slow"); 
        }); 
    }); 
} 

監聽鍵盤按鍵

鍵盤監聽則使用 keypress() 方法,透過 e.which 取得按下的按鍵值,再對應到不同的區塊。雖然頁面上較少用到按鍵監聽,但這個範例頗具新意,值得參考:

$(document).keypress(function(e) 
    { 
        switch(e.which) 
        { 
             // user presses the "a" 
             case 97:    showViaKeypress("#home"); 
                        break;   
             // user presses the "s" key 
             case 115:   showViaKeypress("#about"); 
                        break; 
             // user presses the "d" key 
             case 100:   showViaKeypress("#contact"); 
                     break; 
             // user presses the "f" key 
             case 102:   showViaKeypress("#awards"); 
                     break; 
             // user presses the "g" key  
             case 103:   showViaKeypress("#links"); 
        } 
    });

按 a、s、d、f、g 鍵就能滑動切換到不同區塊,讓鍵盤操作變得直覺又有趣。

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