jQuery实现输入框聚焦,键盘上下键选择城市
在最近有个项目中 需要实现当文本框聚焦的时候,可以键盘上下键选择内容,按enter键的时候,把内容传到输入框中,如图所示:
实现代码如下:
/** *输入框聚焦,键盘上下键选择城市 */ ;(function($){ $.fn.inputKey=function(options){ var settings=$.extend({ 'focusID':'#city2',//聚焦的输入框ID或class 'slideBox':'.FdestinationBox',//内容容器Div 'current':'current',//li有选中状态的class名 'dataCity':'data-city'//li上的属性 如:<li data-city="北京"></li> },options); return this.each(function(){ var number = 0; var $focusDiv = $(settings.focusID); var $slideBox = $(settings.slideBox); var $slideBoxLi = $slideBox.find('li'); var sizeLength = $slideBox.find('li').size(); $focusDiv.focus(function(){ // sizeLength = $slideBox.find('li').size(); $slideBoxLi.removeClass(settings.current);//初始化current状态 $slideBox.css({'display':'block'}); }); if(window.addEventListener){ $focusDiv[0].addEventListener("input", function () { number = 0; sizeLength = $slideBox.find('li').size(); $slideBoxLi.removeClass(settings.current); $slideBoxLi.eq(0).addClass(settings.current); }); }else{ $focusDiv[0].attachEvent("input", function () { number = 0; sizeLength = $slideBox.find('li').size(); $slideBoxLi.removeClass(settings.current); $slideBoxLi.eq(0).addClass(settings.current); }); } $focusDiv.on('keyup',function(e){ console.log(sizeLength); e=window.event||e; if(e.keyCode==38){ if(number>0){ number--; }else{ number=sizeLength-1; } $slideBoxLi.removeClass(settings.current); $slideBoxLi.eq(number).addClass(settings.current); } else if(e.keyCode==40){ if(sizeLength-1 > number){ number++; }else{ number=0; } $slideBoxLi.removeClass(settings.current); $slideBoxLi.eq(number).addClass(settings.current); } else if(e.keyCode==13){ var dataCity = $slideBoxLi.eq(number).attr(settings.dataCity); $focusDiv.val(dataCity); $slideBox.fadeOut(); $focusDiv.blur(); $slideBoxLi.removeClass(settings.current); } }); $slideBoxLi.hover(function(){ number=$(this).index(); $slideBoxLi.removeClass(settings.current); $(this).addClass(settings.current); }); $('body').on('click',$slideBoxLi,function(e){ e.preventDefault(); var dataCity = $slideBoxLi.eq(number).attr(settings.dataCity); $focusDiv.val(dataCity); number=0; }); }); } })(jQuery);
调用的方式:
$(function(){ $("#city2").inputKey({ 'focusID':'#city2', 'slideBox':'.FdestinationBox', 'current':'current', 'dataCity':'data-city' }); })