基于Jquery实现键盘按键监听

前端技术 2023/09/03 JavaScript

从NETTUTS看到的文章,效果很不错,有点类似于Flash做出来的效果,demo在这里 ,原文 对实现步骤讲得很清楚,我就不多提了,实现效果的逻辑比较简单,也就是slideDown()方法,

jquery slideDown()方法,实现滑动效果。

复制代码 代码如下:

// 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()方法,其实也没什么难度,不过我们很少在页面上使用按键监听,这个例子比较新奇,值得我们参考,如有必要时,可以在项目里用用。

复制代码 代码如下:

$(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\"); 
        } 
    });

本文地址:https://www.stayed.cn/item/6533

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。