html input 输入框自动填充, 自动补全提示
程序员文章站
2022-06-01 16:22:38
...
效果如下:
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<input type="text" id="value" autoComplete="off">
</body>
</html>
<script>
function createstyle(css){
var mystyle=$('#mystyle');
if(!mystyle.length>0){
var style="<style id='mystyle'></style>";
$(document).find('head').append(style);
mystyle=$('#mystyle');
}
mystyle.append(css);
}
function autoShowUser(users,id) {
id=id||"#value";
var wd=$(id)[0].clientWidth;
var hg=$(id)[0].clientHeight;
var suggest='<ul id="suggest" style="display: none;position:absolute;width: '+wd+'px; background-color: white;padding: 0px;margin:0px;"></ul>';
var css_li="#suggest li{display: block;height:"+hg+";font: 14px/25px '微软雅黑','黑体',sans-serif;margin: 0px;color:rgb(66, 139, 202);text-align: left;padding:1px}";
css_li+="#suggest li:hover{cursor: pointer;margin: 0px;background-color: rgb(227,227,227);}";
$(id).after(suggest);
createstyle(css_li);
$(id).bind('keyup click',function (e) {
var name= $(this).val();
var num=0;
if(name!='' ){
var html='';
for (var i=0;i<users.length;i++){
if(users[i].indexOf(name)>-1){
html += "<li>" +users[i]+"</li>";
num++;
}
if(num>9){
break;
}
}
if(html !=''){
$('#suggest').show();
$('#suggest').html(html);
$('#suggest li').css(css_li);
$('#suggest li').bind('click',function(e){
$(id).val($(e.target).html());
$('#suggest').hide();
});
}
}else{
$('#suggest').hide();
}
});
$(id).blur(function () {
setTimeout(function () {
$('#suggest').hide();
},150);
})
}
var users=['22','221','222','223','224','老大','老二','老三'];
autoShowUser(users,'#value') ;
</script>
用法:
调用函数就可以了,users变量存储数组对象 (一般后台传递过来,可以数据加密防止泄露………..),
autoShowUser(users,'#value') ;
上一篇: Libevent 源码阅读--典型应用中的函数调用关系
下一篇: 数据库自动修改 【最后修改时间】