今天写一个案例:就是导航可以用数字键盘来监听,也就是点击数字键盘相应的导航触发并且出现相应的样式。来看代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin:0;padding:0;}
ul,li{list-style: none}
.nav{overflow: hidden;margin:30px auto;height:60px;width:600px;}
.nav li{float:left;width:100px;text-align:center;height:60px;line-height:60px;background-color: #00c87a;position: relative}
.nav li a{color:#fff;position:absolute;left:0;width:100%;height:100%;text-decoration: none;z-index: 100}
.nav li span{width:100%;height:100%;position:absolute;left:0;top:60px;background-color: #ff8703;z-index: 10}
</style>
</head>
<body>
<ul class="nav">
<li>
<a href="javascript:void(0)">导航1</a>
<span></span>
</li>
<li>
<a href="javascript:void(0)">导航2</a>
<span></span>
</li>
<li>
<a href="javascript:void(0)">导航3</a>
<span></span>
</li>
<li>
<a href="javascript:void(0)">导航4</a>
<span></span>
</li>
<li>
<a href="javascript:void(0)">导航5</a>
<span></span>
</li>
<li>
<a href="javascript:void(0)">导航6</a>
<span></span>
</li>
</ul>
</body>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
$(function(){
$(".nav li").on("mouseenter",function(){
$(this).children("span").stop().animate({top:0})
}).on("mouseleave",function(){
$(this).children("span").stop().animate({top:60})
});
//启用数字键触发mouseenter事件,离开触发mouseleave事件
//bug:按下键盘不弹起,一直在触发,解决不让触发下一次的问题就是增加节流阀,即设置一个开关,键盘按下去让其为false;弹起为true
var flag=true;
$(document).on("keydown",function(e){
if(flag){
flag=false;
var code = e.keyCode;//获取键盘的code码
if(code>=49 && code<=54){//数字键盘1~6的code是49~54
$(".nav li").eq(code-49).mouseenter();
}
}
});
$(document).on("keyup",function(e){
flag=true;
var code = e.keyCode;
if(code>=49 && code<=54){
$(".nav li").eq(code-49).mouseleave();
}
})
})
</script>
</html>
当点击数字键盘3时候效果图如下: