请知悉:本文最近一次更新为 10年 前,文中内容可能已经过时。

项目要用,竟然研究了一天,仔细参考了邮件提示插件以及https://www.iteye.com/problems/52682,搞明白了如何实现。具体代码如下:
html代码:

<style type="text/css">
.search-bar{height:32px;clear: both;position: relative;z-index: 297;}
.search-bar #searchkey{width:176px;height:30px; line-height:16px;border:1px #ddd solid;padding:0 12px;background-color: #FFF;float: right; border-right:none;font-size: 13px;}
.search-bar #searchkey:hover{border:1px #c3c3c3 solid;border-right:none;}
.searchsugbox {
position: absolute;
width: 458px;
border: 1px solid #dddddd;
right:40px;
top:32px;
display: none;
border-top: none;
}
.searchsugbox ul li{height:30px;line-height: 30px;padding: 0 12px; background-color: #FFF;cursor: pointer;font-size: 12px;list-style:none;}
.searchsugbox ul li:hover,#hoverli{background-color: #f2fbfa;}
</style>
<div style="width:510px;height:250px;margin:50px auto;padding:10px;float:left;border:1px solid #999;">
<div class="search-bar">
<div class="searchsugbox" style="display:none;">
<ul class="search-interest">
<li data-key="测试网速">测试<b>网速</b></li>
<li data-key="测试网速2">测试<b>网速</b></li>
<li data-key="测试网速3">测试<b>网速</b></li>
<li data-key="测试网速4">测试<b>网速</b></li>
</ul>
</div>
<input id="searchkey" autocomplete="off" onkeydown="JavaScript:if(event.keyCode==13) search('key');" type="text"/>
</div>
</div>

模块中的代码:

define(function(require, exports, module) {

var $ = require('$');
/*调用示例
var chooselibykey=require('chooselibykey');
chooselibykey.chooselibykey('.search-interest li','#searchkey');
*/
exports.chooselibykey = function(li,input) {
//一些全局变量
var liveValue,linum,index;
var index = -1;
function changeinputtext(){
if(index>linum){index=1;}else if(index==0||index==-1){index=linum;}
$(li).attr("id","");
$('#tip').html($(li).eq(index).attr("data-key")+"|"+index);
$(li).eq(index).attr("id","hoverli");
liveValue = $(li).eq(index).attr("data-key");
$(input).val(liveValue);
}
$(li).live("click",function() {
liveValue = $(this).attr("data-key");
$(input).val(liveValue);
index=$(this).index();
});
$(li).live("hover",function() {
$(li).attr("id","");
liveValue = $(this).attr("data-key");
$(input).val(liveValue);
index=$(this).index();
});
$(input).focus(function() {
$(input).keyup(function(e) {
//如果按键是上下键
linum=$(li).length-1;
if (e.keyCode === 38) {
if(index==-1){
index=linum;
}else{
index--;
}
changeinputtext();
}else if(e.keyCode === 40){
if(index==-1){
index=1;
}else{
index++;
}
changeinputtext();
}else if(e.keyCode === 13 && $(this).val()!=''){
alert("搜索对应关键词");
}else{
//ajax获取关键词的推荐
}
});
});
};
});

主要思想:监听input聚焦后的键盘按键,对上下等按键进行响应并修改li的背景色,将li的值置入到input中。


如您从本文得到了有价值的信息或帮助,请考虑扫描文末二维码捐赠和鼓励。

尊重他人劳动成果。转载请务必附上原文链接,我将感激不尽。


与《SeaJS-ul li键盘选择模块》相关的博文:


留言

avatar
😀
😀😁😂😅😭🤭😋😘🤔😰😱🤪💪👍👎🤝🌹👌