输入框简单智能匹配
html中
<div class="box">
<input type="text" name="myname" id="myId" />
<ul id="result"></ul>
</div>
js
$(document).ready(function(){
$('#myId').on('input propertychange',function(e){
e.stopPropagation();
searchResult(e);
})
})
var arr=['ada','dgr','arjvb','bshs','bb','ahsh'];
var result= $('#result');
var myinput=$('#myId');
function searchResult(e){
var str = e.target.value;
var reg=new RegExp(str);
var olist ='';
for(var i in arr){
if(reg.test(arr[i])){
olist+='<li class="li-item" onclick="chooseItem(event)">'+arr[i]+'</li>';
}
}
result[0].innerHTML = olist;
result.css('display','block');
e.stopPropagation();
}
function chooseItem(e){
var lidom = e.target;
var value = lidom.innerText;
myinput.val(value);
$('#result').css('display','none');
}
style内部
.box{
position:relative;
}
#result{
position:absolute;
top:20px;
left:0;
width:180px;
max-height:100px;
overflow-y:auto;
z-index:10;
}
ul{
display:none;
position:absolute;
top;40px;
background-color:#fff;
}
li{
margin:0;
padding:0;
list-style:none;
line-height:20px;
border-radius:5px;
border:1px solid #fff;
}
li:hover{
background-color:#1876ca;
color:#ffffff;
}