在此代码中,我使用鼠标悬停菜单,但现在我想使用键盘键输入此菜单并输入键。我想使用选项卡导航此菜单,并且在主菜单子菜单上按Enter键应该展开,并且应该使用向上和向下箭头键导航此子菜单
<!DOCTYPE html>
<html>
<head>
<style>
#menu {
width: 608px;
margin-top: 0px;
margin-right: auto;
margin-bottom: 0px;
margin-left: auto;
padding-top: 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
}
#menu ul {
margin: 0px;
padding: 0px;
}
#menu ul li {
background-color: #666;
float: left;
border: 1px solid #CCC;
position: relative;
list-style-type: none;
}
#menu ul li:hover ul {
visibility: visible;
background-color: #333;
}
#menu ul li a {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
font-size: 14px;
line-height: 30px;
color: #FFF;
text-decoration: none;
text-align: center;
display: block;
height: 30px;
width: 150px;
}
#menu ul ul {
position: absolute;
visibility: hidden;
left: -1px;
top: 31px;
}
#menu ul li:hover {
background-color: #333;
}
#menu ul li ul li a:hover {
background-color: #069;
}
#menu ul li a:hover {
color: #0FF;
}
#leftmenu {
position: absolute;
left: 165px;
top: 20px;
}
#rightmenu {
position: absolute;
right: 164px;
top: 20px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>
<div id="menu">
<ul id='leftmenu'>
<li><a href="#" rel="submenu1">BOAT</a>
<div id="submenu1">
<ul>
<li><a href='#'>Specs & Boat Plans</a></li>
<li><a href='#'>Itineraries</a></li>
<li><a href='#'>Exteriors</a></li>
<li><a href='#'>Diving & Water Toys</a></li>
</ul>
</div>
</li>
</ul>
<ul id='rightmenu'>
<li><a href="#" rel="submenu2">LIFE ON BOARD</a>
<ul>
<div id="submenu2">
<li><a href='#'>Itineraries</a></li>
<li><a href='#'>Dining</a></li>
<li><a href='#'>Family Fun</a></li>
<li><a href="#">Lifelong Learning</a></li>
<li><a href="#">The Crew</a></li>
</ul>
</div>
</li>
</ul>
</div>
</body>
</html>
答案 0 :(得分:0)
您必须绑定keydown事件并从此事件处理keyCode。 取决于事件键码您必须触发点击或执行操作。
$(document).on('keydown', function(event){
// if You want to bind arrow keys only on menu
// change document to selector of menu.
if (event.keyCode === xx) {
/* in place of xx arrow or enter code
FULL LIST HERE: http://www.javascripter.net/faq/keycodes.htm */
$('#selector for next or previous element here').trigger('click');
} else if (event.keyCode === yy) {
// do something else
} //etc...
});
答案 1 :(得分:0)
就像说的那样,你应该将关键事件绑定到DOM
var isLeft = true;
var sub1 = document.getElementById('submenu1').getElementsByTagName('li');
var sub2 = document.getElementById('submenu2').getElementsByTagName('li');
$('body').keyup(function(e){
if(e.which === 9){
if (isLeft){
setVisible(sub2, false);
setVisible(sub1, true);
isLeft = false;
}else{
setVisible(sub1, false);
setVisible(sub2, true);
isLeft = true;
}
}
})
function setVisible(x, flag){
for (var i = 0; i < x.length; i++){
if (flag){
x[i].style.visibility = 'visible';
}else{
x[i].style.visibility = 'hidden';
}
}
}
这是一个小Example