您的位置:首页 > Web前端 > JavaScript

利用JS实现键盘控制下拉列表的滚动

2014-05-07 19:55 791 查看
昨晚自己倒腾的。估计这种代码只有自己看得懂了。第一篇博文,纪念一下。

代码插入这个还是比较方便的~~

var keyHandler=function(event){
var e = event || window.event || arguments.callee.caller.arguments[0];
var hoverCSS={
color: '#FFF',
'background-color': '#6E9DE4'
};
var backCSS={
color:'#000',
'background-color':'#fff'
};
if(e && e.keyCode==37){ // 按 左
cu_pos--;
$("#hh_"+dest).find('li').eq(cu_pos+1).find('a').css(backCSS);
if(cu_pos<0){
cu_pos=$("#hh_"+dest).find('li').length-1;
}
$("#hh_"+dest).animate({scrollTop:cu_pos*25},100);
$("#hh_"+dest).find('li').eq(cu_pos).find('a').css(hoverCSS);
}
if(e && e.keyCode==38){ // 按 上
//要做的事情

cu_pos--;
//  console.log("Pressed 上"+cu_pos);

$("#hh_"+dest).find('li').eq(cu_pos+1).find('a').css(backCSS);
if(cu_pos<0){
cu_pos=$("#hh_"+dest).find('li').length-1;
}
$("#hh_"+dest).animate({scrollTop:cu_pos*25},100);
$("#hh_"+dest).find('li').eq(cu_pos).find('a').css(hoverCSS);

}
if(e && e.keyCode==39){ // enter 右
cu_pos++;
// if(cu_pos>=0){
$("#hh_"+dest).find('li').eq(cu_pos-1).find('a').css(backCSS);
//$("#hh_"+dest).css("marginTop","-=12px");

//  }
if(cu_pos>=$("#hh_"+dest).find('li').length){
cu_pos=0;
}
$("#hh_"+dest).animate({scrollTop:cu_pos*25},100);

$("#hh_"+dest).find('li').eq(cu_pos).find('a').css(hoverCSS);

}
if(e && e.keyCode==40){ // enter 下
cu_pos++;
//  console.log("Pressed 下"+cu_pos);
// console.log(cu_pos);
//   console.log($("#hh_"+dest).find('li').length);

// if(cu_pos>0){
$("#hh_"+dest).find('li').eq(cu_pos-1).find('a').css(backCSS);
//  $("#hh_"+dest).css("marginTop","+=12px");

//   }
if(cu_pos>=$("#hh_"+dest).find('li').length){
cu_pos=0;
}
$("#hh_"+dest).animate({scrollTop:cu_pos*25},100);
$("#hh_"+dest).find('li').eq(cu_pos).find('a').css(hoverCSS);

}
if(e && e.keyCode==13){ // enter Enter
// console.log("Pressed Enter");
// console.log($("#hh_"+dest).find('li').eq(cu_pos).find('a').html());
gets_id('class_'+dest).value=$("#hh_"+dest).find('li').eq(cu_pos).find('a').html();
$("#hh_"+dest).find('li').eq(cu_pos).find('a').css(backCSS);
gets_id('hh_'+dest).style.display='none';
document.removeEventListener("mousedown", handler, false);
document.removeEventListener("keydown", keyHandler, false);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息