求大神幫忙 第二句是別人打給我參考的
看下代碼,真挺麻煩
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<style>
li {float:left; height:50px; width:50px; background:#ccc; list-style:none; margin-left:5px;}
li.curr {background:red;}
</style>
<script type='text/javascript'>
function hasClass(obj, sCls){
return obj.className.match(new RegExp("\\b"+sCls+"\\b", "i"));
}
function addClass(obj, sCls){
var blank=(obj.className!="")?" ":"";
if(!hasClass(obj, sCls))obj.className+=blank+sCls;
}
function removeClass(obj, sCls){
var re=new RegExp("(\\s|^)"+sCls+"(\\s|$)", "i");
if(hasClass(obj, sCls))obj.className=obj.className.replace(re, "");
}
function prevAll(arr,sCls){
var index=0;
for(var i=0;i<arr.length;i++){
if(hasClass(arr[i],sCls))index=i;
}
return index;
}
window.onload=function(){
var aLi=document.getElementsByTagName('li'), index;
var movePrev = function (){
index=prevAll(aLi,'curr');
if(index==0){//可循環移動
removeClass(aLi[index],'curr');
addClass(aLi[aLi.length-1],'curr');
index = aLi.length-1;
console.log(index);
}else{
removeClass(aLi[index],'curr');
addClass(aLi[index-1],'curr');
index--;
console.log(index);
}
}
var moveNext = function (){
index=prevAll(aLi,'curr');
if(index==aLi.length-1){//可循環移動
removeClass(aLi[aLi.length-1],'curr');
addClass(aLi[0],'curr');
index = 0;
}else{
removeClass(aLi[index],'curr');
addClass(aLi[index+1],'curr');
index++;
}
}
document.onkeydown=function(e){
var e = e || event,
code = e.keyCode || e.which;
code==38 && movePrev();
code==40 && moveNext();
}
};
</script>
</head>
<body>
<ul>
<li class='curr'></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>