RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:00-18:00
你可能遇到了下面的问题
关闭右侧工具栏
支持键盘按键的jQuery导航应用
  • 作者:admin
  • 发表时间:2013-07-02 14:17:18
  • 来源:未知

在本文中我将为您介绍如何侦听用户键盘按键事件,通过使用键盘来切换导航菜单,也为用户提供了方便,从而使导航功能更加实用。

查看演示DEMO 下载源码

XHTML



Welcome!

Some Text

About me

Some Text

Product

Some Text

Service

Some Text

My Blog

Some Text

创建一个包含导航菜单#nav和菜单对应的内容.box,注意导航菜单中含有对应的字母就是要用到的键盘按键导航功能。

CSS

#nav{width:460px; margin:0 auto}
#nav ul{list-style:none; height:24px}
#nav ul li{float:left; font-size:14px; font-weight:bold}
#nav ul li a{display:block; color:#369; margin-right:20px}
#nav ul li a:hover{color:#f90}
.box{width:400px; height:300px; margin:20px auto; padding:10px 20px; line-height:22px}
.box h2{padding:5px 10px; width:200px; background:#9cf; color:#fff}
#home{background:#15add1}
#about{background:#fdc700}
#product{background:#f80083}
#service{background:#f18300}
#blog{background:#98c313}

以上CSS代码将导航菜单设置为一行,为了演示,我给每个导航菜单对应的模块内容背景设置了不同的颜色。

jQuery

关键来看jQuery,首先要引用jquery库,以及我分离出来的一个keynav.js文件。


接下来在keynav.js文件中准备两个函数,一个是当用户按键操作时用来调用的函数showViaKeypress(),当用户按键时,导航对应的模块显示出来,其他模块隐藏,请看代码:

function showViaKeypress(element_id){
	$(".box").css("display","none");
	$(element_id).slideDown("slow");
}

另一个函数showViaLink(),简单的说是用一个数组处理当用户点击导航菜单时,链接对应的模块。即当用户不使用键盘按键操作时还可以使用常规的鼠标点击方法来导航。

function showViaLink(array){
	array.each(function(i){
		$(this).click(function(){
			var target = $(this).attr("href");
			$(".box").css("display","none");
			$(target).slideDown("slow");
		});
	});
}

最后,当页面加载的时候,jQuery要处理以下事情:

1、除了首页#home模块显示外,其他导航对应的模块都要先隐藏。

2、调用showViaLink()函数,相应点击导航链接。

3、侦听用户按键操作,调用showViaKeypress()函数,完成切换导航功能。

$(function(){
	$(".box").css("display","none");
	$("#home").css("display","block");

	showViaLink($("#nav ul li a"));

	// listens for any navigation keypress activity
	$(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("#product");
				break;

			// user presses the "f" key
			case 102:
			    showViaKeypress("#service");
				break;

			// user presses the "g" key
			case 103:
			   showViaKeypress("#blog");
		}
	});
});

注意使用ASCII值,侦听到用户按下的键值,如小写的“a”对应的ASCII值是“97”