基于jquery+html+css的搜索索引
下面开始贴代码了
html:
<div class="all">
<!--昵称查找-->
<div class="search">
<input id="search_text" placeholder='输入搜索内容' type='text'>
<div id="auto_div" style="display:none;"></div>
</div>
</div>
css:
.all{
width:95%;
position:absolute;
top:2%;
left:5%;
}
#auto_div
{
position: absolute;
left: 0;
z-index: 1;
min-width: 500px;
box-sizing: border-box;
list-style: none;
padding: 0;
border-radius: .3em;
margin: .2em 0 0;
background: hsla(0,0%,100%,.9);
background: linear-gradient(to bottom right, white, hsla(0,0%,100%,.8));
border: 1px solid rgba(0,0,0,.3);
box-shadow: .05em .2em .6em rgba(0,0,0,.2);
text-shadow: none;
}
#search_text{
width: 500px;
padding-left: 10px;
height: 30px;
border-radius: 3px;
border: 1px solid rgb(236, 225, 225);
}
js:(使用前先引用jquery.min.js,版本都可以我用的是:jquery-1.8.3.min.js )
//测试用的数据
var test_list = ["百度搜索","天气预报","谷歌搜索","火狐搜索","糗事百科","搜索文章",];
var test_lists = "";
var old_value = "";
var highlightindex = -1;
//自动完成
function AutoComplete(auto, search, mylist) {
if ($("#" + search).val() != old_value || old_value == "") {
var autoNode = $("#" + auto); //缓存对象(弹出框)
var carlist = new Array();
var n = 0;
old_value = $("#" + search).val();
for (i in mylist) {
if (mylist[i].indexOf(old_value) >= 0) {
carlist[n++] = mylist[i];
}
}
autoNode.empty(); //清空上次的记录
var count=0;
for (i in carlist) {
if(++count>10)break;
var wordNode = carlist[i]; //弹出框里的每一条内容
var newDivNode = $("<div>").attr("id", i); //设置每个节点的id值
newDivNode.attr("style", "font:14px/25px arial;height:25px;padding:0 8px;cursor: pointer;");
newDivNode.html(wordNode).appendTo(autoNode); //追加到弹出框
//鼠标移入高亮,移开不高亮
newDivNode.mouseover(function () {
if (highlightindex != -1) {//原来高亮的节点要取消高亮(是-1就不需要了)
autoNode.children("div").eq(highlightindex).css("background-color", "white");
}
//记录新的高亮节点索引
highlightindex = $(this).attr("id");
$(this).css("background-color", "#ebebeb");
});
newDivNode.mouseout(function () {
$(this).css("background-color", "white");
});
//鼠标点击文字上屏
newDivNode.click(function () {
//取出高亮节点的文本内容
var comText = autoNode.hide().children("div").eq(highlightindex).text();
highlightindex = -1;
//文本框中的内容变成高亮节点的内容
$("#" + search).val(comText);
})
if (carlist.length > 0) { //如果返回值有内容就显示出来
autoNode.show();
} else { //服务器端无内容返回 那么隐藏弹出框
autoNode.hide();
//弹出框隐藏的同时,高亮节点索引值也变成-1
highlightindex = -1;
}
}
}
}
$(function () {
old_value = $("#search_text").val();
$("#search_text").focus(function () {
if ($("#search_text").val() == "") {
AutoComplete("auto_div", "search_text", test_lists);
}
});
$("#search_text").keyup(function () {
if ($("#search_text").val() == "") {
AutoComplete("auto_div", "search_text", test_lists);
document.getElementById('auto_div').style.display = "none";
}else{
AutoComplete("auto_div", "search_text", test_list);
}
});
});
这样就完成了。需要修改test_list的值为自己得到的值。
以前用到过,希望能帮助你!