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