JS获取键盘方向键,然后执行相应的响应事件。以一个简单的图片的左右切换为例,代码如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<mce:style type="text/css"><!--
.list {
font-size:20px;
text-align:center;
line-height:40px;
}
--></mce:style><style type="text/css" mce_bogus="1">.list {
font-size:20px;
text-align:center;
line-height:40px;
}</style>
<mce:script type="text/javascript"><!--
var menuArray = [
{info:"栏目一",url:"#"},
{info:"栏目二",url:"#"},
{info:"栏目三",url:"#"},
{info:"栏目四",url:"#"}
];
var menuPos = 0;
var menuSize = 4;
function $(id){
return document.getElementById(id);
}
function showMenu(){
for(var i=0;i<menuSize;i++){
$("menu"+i).innerHTML = menuArray[i].info;
$("menu"+i).style.backgroundImage = "url(menu_focus0.gif)";
}
}
function menuFocus(num){
//$("menu"+menuPos).style.backgroundColor = "#CCCCCC";
$("menu"+menuPos).style.backgroundImage = "url(menu_focus0.gif)";
$("menu"+menuPos).style.color = "#000000";
$("menu"+menuPos).style.fontSize = "20px";
menuPos+=num;
if(menuPos>menuArray.length-1) menuPos=0;
else if(menuPos<0) menuPos=menuArray.length-1;
//$("menu"+menuPos).style.backgroundColor = "#00CCFF";
$("menu"+menuPos).style.backgroundImage = "url(menu_focus1.gif)";
$("menu"+menuPos).style.color = "#FFFFFF";
$("menu"+menuPos).style.fontSize = "30px";
}
function deSelect(){
location.href = menuArray[menuPos].url;
}
function init(){
showMenu();
menuFocus(0);
}
document.onsystemevent = grabEvent;
document.onkeypress = grabEvent;
document.onirkeypress = grabEvent;
document.onkeyup = grabEvent;
function grabEvent(){
var keycode = event.which||event.keyCode;
switch(keycode){
case 1:
case 38:
case 269: //up
return 0;
break;
case 40:
case 2:
case 270: //down
return 0;
break;
case 37:
case 3:
case 271: //left
menuFocus(-1);
return 0;
break;
case 39:
case 4:
case 272: //right
menuFocus(1);
return 0;
break;
case 13: //enter
deSelect();
return 0;
break;
case 339: //exit
case 340: //back
location.href = "../index.htm";
return 0;
break;
}
}
// --></mce:script>
</head>
<body leftmargin="0" topmargin="0" οnlοad="init()">
<div style="position:absolute; left:0px; top:0px; width:640px; height:50px; line-height:50px; font-size:30px; color:#FFFFFF; text-align:center; background:#00CCFF;">菜单交互(背景交互)</div>
<div style="position:absolute; left:0px; top:100px; width:640px; height:40px;">
<table width="620" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="140" height="40" class="list" id="menu0"></td>
<td width="20"></td>
<td width="140" class="list" id="menu1"></td>
<td width="20"></td>
<td width="140" class="list" id="menu2"></td>
<td width="20"></td>
<td width="140" class="list" id="menu3"></td>
</tr>
</table>
</div>
</body>
</html>