我想只使用向上和向下箭头键在我的html中导航列表。我找到了很多解决方案并尝试了这个http://jsfiddle.net/mkamithkumar/kgEwT/1/,但它不起作用
我也在http://jsfiddle.net/Vtn5Y/中尝试此代码,箭头键无法导航。
这是我的代码:
<html>
<head>
<link href="jquery/jquery-ui.css" rel="stylesheet">
<script rel="stylesheet" type="text/css">
li.selected {background:yellow}
</script>
<script src="jquery-3.1.0.js"></script>
</head>
<body>
<script >
var li = $('li');
var liSelected;
$(window).keydown(function(e){
if(e.which === 40){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.next();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = li.eq(0).addClass('selected');
}
}else{
liSelected = li.eq(0).addClass('selected');
}
}else if(e.which === 38){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.prev();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = li.last().addClass('selected');
}
}else{
liSelected = li.last().addClass('selected');
}
}
});
</script>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
答案 0 :(得分:1)
尝试这样 - http://pastebin.com/J0wHL5j3
<html>
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<style>
li.selected {background:yellow}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var li = $('li');
var liSelected;
$(window).keydown(function(e){
if(e.which === 40){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.next();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = $(li).first().addClass('selected');
}
}else{
liSelected = $(li).first().addClass('selected');
}
}else if(e.which === 38){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.prev();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = li.last().addClass('selected');
}
}else{
liSelected = li.last().addClass('selected');
}
}
});
});
</script>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
我做的唯一两件事就是在document.ready语句中添加你的代码。 我也不是百分百肯定,但我还没有看到
<script rel="stylesheet" type="text/css">
更有可能使用
<style type="text/css">
在本地完成这两件事后,似乎工作正常。