js捕获键盘按键值,并且实现焦点切换

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>content</title>
		<style type="text/css">
		#nav{
			font-size: 30px;
		}
		#nav_tab{
			position: absolute;
			left: 50%;
			margin-left: -240px;
			margin-top: 40px;
			height: 50px;
			width: 480px;
			line-height: 20px;
			text-align: center;
			background-color: #CCCCCC;
			border: 1px solid black;			
			border-collapse: collapse;
		}
		#nav_tab td{

			border:1px solid black;
		}
		</style>
	</head>
	<body οnlοad="init();" οnshοw="show()">
		<div id="nav">我是内容页</div>
			<table id="nav_tab">
			<tr>
				<td id="num1">菜单一</td>
				<td id="num2">菜单二</td>
				<td id="num3">菜单三</td>
				<td id="num4">返回首页</td>
			</tr>
			</table>
		<script type="text/javascript">
			document.onkeydown = eventHandler;
			document.onsystemevent = eventHandler;

			var position = 1;									//定义全局变量
			var td_all =document.getElementsByTagName("td");
			var num = td_all.length;

				function eventHandler(){
					var keycode=event.which;
					switch (keycode){					
						case 37:                   //左键键值。按下左键时,焦点左移

							changeFocus(-1);
							return false;
							break;

						case 39:           			//右键键值。按下右键时,焦点右移
							changeFocus(+1);
							return false;
							break;

						// case 13:
						

						//  if (position==num) {			//设置当焦点在最后一栏按enter键时返回index页面(BToA)
						// 	skip();
						// }
				}
			}

			function $(id){
				return document.getElementById(id);
			}

			function init(){						//初始化页面焦点
				$("num1").style.backgroundColor="#FFB400";
			}
<!--------------------------实现焦点切换---------------------------------------------------->

			function getFocus(_posNow){				//失去焦点

				$("num"+_posNow).style.backgroundColor="#FFB400";
			}
			function loseFocus(_posPast){			//获得焦点

				$("num"+_posPast).style.backgroundColor="#CCCCCC";
			}
			
			function changeFocus(_move){				//移动焦点
                
				loseFocus(position);

				position+=_move;

				if (position<1) {

					position=num;

				}
				if (position>num) {
					position=1;
				}
				getFocus(position);
				

			}
<!--------------------------实现焦点切换---------------------------------------------------->

		

			function show(){						//每次进入页面时都保持焦点在第一个
				loseFocus(4);
				position=1;									
				$("num"+position).style.backgroundColor="#FFB400";
						
			}

				
			
		</script>
	</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值