这几天公司要做一个和google搜索差不多的一个搜索下拉别表..
<div id="suggestions">
</div>
<script type="text/javascript">
var currentindex = -1;
var size = 0;
var currentTxt;
function getSuggestion(w) {
var url = $("#word").attr("url");
var t = setTimeout(function () {
$.getJSON(url, { w: w }, showData);
}, 500);
}
function showData(data) {
var suggestions = $("#suggestions").html("");
var input = $("#word");
if ($(data).length > 0) {
$(data).each(function (i, it) {
suggestions.append('<li >' + it + '</li>');
})
currentindex = -1;
suggestions.show();
suggestions.children("li").click(function () {
input.val($(this).text());
suggestions.hide();
});
size = $("#suggestions li").size();
document.onclick = function (e) {
var e = e ? e : window.event;
var tar = e.srcElement || e.target;
if (tar.id != "suggestions") {
suggestions.hide();
}
}
}
else {
suggestions.hide();
}
}
function movethis(up) {
currentindex = currentindex + (up ? -1 : 1);
if (currentindex == size) {
currentindex = 0;
}
else if (currentindex < 0) {
currentindex = size-1 ;
}
$("#suggestions li").removeClass("suggec");
$($("#suggestions li")[currentindex]).addClass("suggec");
var textvalue = $($("#suggestions li")[currentindex]).text();
$("#word").val(textvalue);
}
$(function () {
var input = $("#word");
var suggestions = $("#suggestions").html("").hide();
input.keyup(function (e) {
if (e.keyCode != 40 && e.keyCode != 38) {
var word = $.trim(input.val());
if (word) {
getSuggestion(word);
}
else {
suggestions.hide();
}
}
});
input.keyup(function (evn) {
if (evn.keyCode == 38) {
movethis(true);
}
else if (evn.keyCode == 40) {
movethis(false);
}
else if (evn.keyCode == 13) {
$("#suggestions").hide();
$(".br").trigger("click");
}
})
$("#suggestions").mouseover(function () { //鼠标滑过
select = $("#suggestions");
select.children("li").mouseover(
function () {
$(this).addClass("suggec");
currentindex = $("#suggestions li").index(this);
});
}).mouseout(function () { //鼠标滑出
$("#suggestions li").removeClass("suggec");
});
suggestions.width(input.outerWidth() - 1);
})
</script>
ajax.aspx
/*取到的json串.这边可以自己处理一下数据*/
["<span><b>魔法</b>提琴手</span>","<span><b>魔法</b>少女奈叶StrikerS</span>","<span><b>魔法</b>少女奈叶A's</span>","<span><b>魔法</b>少女奈叶</span>","<span><b>魔法</b>护士小麦</span>","<span><b>魔法</b>战士李维
</span>","<span><b>魔法</b>阵都市</span>","<span><b>魔法</b>奇缘</span>","<span><b>魔法</b>先生涅吉!</span>","<span><b>魔法</b>先生涅吉!</span>","<span><b>魔法</b>少女砂沙美</span>","<span><b>魔法</b>战士李维
</span>","<span><b>魔法</b>咪路咪路Charming</span>","<span><b>魔法</b>使派遣会社</span>","<span><b>魔法</b>小歌王</span>","<span><b>魔法</b>使的注意事项</span>","<span><b>魔法</b>学园MA</span>
","<span><b>魔法</b>先生 涅吉!~白翼 ALA ALBA~</span>","<span><b>魔法</b>禁书目录</span>","<span><b>魔法</b>保姆麦克菲</span>"]