1:引用JQuery类库
2:引用autoComplete.js类
简单Demo
1:前端代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jQuery/jquery.js">script>
<script src="jQuery/autoComplete.js">script>
<title>title>
head>
<body>
<div>
<label>用户:label><input type="text" id="actId" maxlength="12" value="" data-id="" />
div>
body>
<script type="text/javascript">
var oo = new mSift('oo', 20, function (str) {
});
oo.SourceUrl = "Handler/Handler.ashx";
oo.Create(document.getElementById('actId'));
script>
html>
2:Handler.ashx页面
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
string name = context.Request.Form["key"];
string str = UserInfo(name);
context.Response.Write(str);
}
public string UserInfo(string Num) {
SqlConnection conn = new SqlConnection("server=.;database=EM_UseSeal;uid=sa;pwd=123456");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from UserInfo where UserName like '%" + Num + "%'", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
StringBuilder sb = new StringBuilder(512);
if (dt != null && dt.Rows.Count > 0) {
sb.Append("[");
foreach (DataRow item in dt.Rows) {
sb.AppendFormat("'{0}|{1}-(编号{2})|{3}${4}',", item["UserNumer"], item["UserName"], item["UserNumer"], item["DepartMentID"], item["DepartMentName"]);
}
sb.Replace(',', ']', sb.Length - 1, 1);
}
return sb.ToString();
}
3:autoComplete.js类
function mSift_SeekTp(oObj, nDire) {
if (oObj.getBoundingClientRect && !document.all) {
var oDc = document.documentElement;
switch (nDire) {
case 0: return oObj.getBoundingClientRect().top + oDc.scrollTop;
case 1: return oObj.getBoundingClientRect().right + oDc.scrollLeft;
case 2: return oObj.getBoundingClientRect().bottom + oDc.scrollTop;
case 3: return oObj.getBoundingClientRect().left + oDc.scrollLeft;
}
} else {
if (nDire == 1 || nDire == 3) {
var nPosition = oObj.offsetLeft;
}
else {
var nPosition = oObj.offsetTop;
}
if (arguments[arguments.length - 1] != 0) {
if (nDire == 1) {
nPosition += oObj.offsetWidth;
}
else if (nDire == 2) {
nPosition += oObj.offsetHeight;
}
} if (oObj.offsetParent != null) {
nPosition += mSift_SeekTp(oObj.offsetParent, nDire, 0);
} return nPosition;
}
}
function mSift(cVarName, nMax, callback) { this.oo = cVarName; this.Max = nMax; this.callback = callback; }
mSift.prototype = {
Varsion: 'v2015.3.11',
Target: Object,
TgList: Object,
Listeners: null,
SelIndex: 0,
Data: [],
SourceUrl: "",
CharLen: 1,
ReData: [],
Create: function (oObj) {
var _this = this;
var oUL = document.createElement('ul');
oUL.style.display = 'none';
oObj.parentNode.insertBefore(oUL, oObj);
_this.TgList = oUL;
oObj.onkeydown = oObj.onclick = function (e) { _this.Listen(this, e); };
oObj.onblur = function () { setTimeout(function () { _this.Clear(); }, 100); };
},
Complete: function () { },
Select: function () {
var _this = this;
if (_this.ReData.length > 0) {
_this.Target.setAttribute("data-id", _this.GetKeyValue(_this.ReData[_this.SelIndex]).key);
_this.Target.value = _this.GetKeyValue(_this.ReData[_this.SelIndex]).value.replace(/\*/g, '*').replace(/\|/g, '|');
_this.callback && _this.callback(_this.GetKeyValue(_this.ReData[_this.SelIndex]).other);
_this.Clear();
}
else {
_this.Target.setAttribute("data-id", "");
}
setTimeout(function () { _this.Target.focus(); }, 10);
_this.Complete();
},
Listen: function (oObj) {
var _this = this;
_this.Target = oObj;
var e = arguments[arguments.length - 1];
var ev = window.event || e;
switch (ev.keyCode) {
case 9://TAB
return;
case 13://ENTER
_this.Target.blur();
_this.Select();
return;
case 38://UP
_this.SelIndex = _this.SelIndex > 0 ? _this.SelIndex - 1 : _this.ReData.length - 1;
break;
case 40://DOWN
_this.SelIndex = _this.SelIndex < _this.ReData.length - 1 ? _this.SelIndex + 1 : 0;
break;
default:
_this.SelIndex = 0;
}
if (_this.Listeners) { clearInterval(_this.Listeners); }
_this.Listeners = setInterval(function () {
_this.Get();
}, 50);
},
getData: function (fn) {
var _this = this;
$.ajax({
type: "post",
url: _this.SourceUrl,
cache: false,
data: { key: _this.Target.value },
success: function (data) {
data = eval('(' + data + ')');
fn(data);
},
error: function (e) {
console.log(e);
}
});
},
Get: function () {
var _this = this;
if (_this.Target.value == '') { _this.Clear(); return; }
if (_this.Listeners) { clearInterval(_this.Listeners); };
if (_this.Target.value.length >= _this.CharLen) {
if (_this.SourceUrl.length > 0) {
_this.getData(function (json) {
_this.Data = json;
todo();
});
} else {
todo();
}
} else {
_this.callback && _this.callback("");
_this.Target.setAttribute("data-id", "");
}
function todo() {
_this.ReData = [];
var cResult = '';
for (var i = 0; i < _this.Data.length; i++) {
if (_this.Data[i].toLowerCase().indexOf(_this.Target.value.toLowerCase()) >= 0) {
_this.ReData.push(_this.Data[i]);
if (_this.ReData.length == _this.Max) { break; }
}
}
var cRegPattern = _this.Target.value.replace(/\*/g, '*');
cRegPattern = cRegPattern.replace(/\|/g, '|');
cRegPattern = cRegPattern.replace(/\+/g, '\\+');
cRegPattern = cRegPattern.replace(/\./g, '\\.');
cRegPattern = cRegPattern.replace(/\?/g, '\\?');
cRegPattern = cRegPattern.replace(/\^/g, '\\^');
cRegPattern = cRegPattern.replace(/\$/g, '\\$');
cRegPattern = cRegPattern.replace(/\(/g, '\\(');
cRegPattern = cRegPattern.replace(/\)/g, '\\)');
cRegPattern = cRegPattern.replace(/\[/g, '\\[');
cRegPattern = cRegPattern.replace(/\]/g, '\\]');
cRegPattern = cRegPattern.replace(/\\/g, '\\\\');
var cRegEx = new RegExp(cRegPattern, 'i');
for (var i = 0; i < _this.ReData.length; i++) {
if (_this.Target.value.indexOf('*') >= 0) {
_this.ReData[i] = _this.ReData[i].replace(/\*/g, '*');
}
if (_this.Target.value.indexOf('|') >= 0) {
_this.ReData[i] = _this.ReData[i].replace(/\|/g, '|');
}
cResult += ''.ChangeOn(this);' + _this.oo + '.SelIndex=' + i + ';" onmousedown="' + _this.oo + '.Select();" data-id=' + _this.GetKeyValue(_this.ReData[i]).key + '>'
+ _this.GetKeyValue(_this.ReData[i]).value.replace(cRegEx, function (s) {
return '' + s + '';
}); +'';
}
if (cResult == '') { _this.callback && _this.callback(""); _this.Target.setAttribute("data-id", ""); _this.Clear(); }
else {
_this.TgList.innerHTML = cResult;
_this.TgList.style.cssText = 'display:block;width: 287px; font-size: 12px;border: 1px rgba(82, 168, 236, 0.8) solid;background-color: #FFF;position: absolute;top: 28px;left: 72px;color: #323232;z-index:2000;';
//_this.TgList.style.cssText = 'display:block;position:absolute;background:#fff;border:#090 solid 1px;margin:-1px 0 0;padding: 5px;list-style:none;font-size:12px;z-index:2000;';
//_this.TgList.style.top = mSift_SeekTp(_this.Target, 0) + 'px';
//_this.TgList.style.left = mSift_SeekTp(_this.Target, 3) + 'px';
//_this.TgList.style.width = _this.Target.offsetWidth - 12 + 'px';
}
var oLi = _this.TgList.getElementsByTagName('li');
if (oLi.length > 0) {
oLi[_this.SelIndex].style.cssText = 'background:#36c;padding:0 5px;line-height:20px;cursor:default;color:#fff;';
}
}
},
GetKeyValue: function (str) {
var arry = str.split("|");
if (arry && arry.length == 1) {
return { key: "", value: arry[0] };
}
else if (arry && arry.length == 2) {
return { key: arry[0], value: arry[1] };
}
else if (arry && arry.length == 3) {
return { key: arry[0], value: arry[1], other: arry[2] };
}
else {
return { key: "", value: "" }
}
},
ChangeOn: function (oObj) {
var oLi = this.TgList.getElementsByTagName('li');
for (var i = 0; i < oLi.length; i++) {
oLi[i].style.cssText = 'padding:0 5px;line-height:20px;cursor:default;';
}
oObj.style.cssText = 'background:#36c;padding:0 5px;line-height:20px;cursor:default;color:#fff;';
},
Clear: function () {
var _this = this;
if (_this.TgList) {
_this.TgList.style.display = 'none';
_this.ReData = [];
_this.SelIndex = 0;
}
}
}
css样式方面要根据实际情况自己来写了。