#search_box {
width: 201px;
height: 31px;
background: url(/image/bg_search_box.gif);
}
#search_box #auto_txt {
float: left;
padding: 0;
margin: 6px 0 0 6px;
border: 0;
width: 159px;
background: none;
font-family:Arial;
font-size: .8em;
}
#search_box #btn_search {
float: right;
margin: 3px 4px 0 0;
}
#auto_div{
position:absolute;
border-width:1px;
border:1px #808080 solid;
}
// 用来判断选中补全的项
var highLightIndex = -1;
// 设定一个timeout时间,防止频繁提交数据到后台
var timeoutId;
// 初始化查询框位置
initSearchText();
//绑定键盘事件
$('#auto_txt').bind('keyup', processKeyup);
//初始化函数设定位置
function initSearchText() {
$('#auto_div').hide();
var pos = $('#auto_txt').position();
var topPosition = pos.top + $('#auto_txt').height() + 88;
var leftPosition = pos.left;
$('#auto_div').offset({ top: topPosition, left: leftPosition });
$('#auto_div').width(170);
}
// 添加键盘事件
function processKeyup(event) {
var myEvent = event || windows.event;
var keyCode = myEvent.keyCode;
// 判断输入的是数字,字母,backspace键
if ((keyCode >= 65 && keyCode <= 90) || keyCode == 8 || keyCode == 32 || (keyCode >= 48 && keyCode <= 57)) {
if ($("#auto_txt").val() == "") {
$('#auto_div').hide();
} else {
highLightIndex = -1;
clearTimeout(timeoutId);
timeoutId = setTimeout(processAjaxRequest, 100);
}
} else if (keyCode == 38 || keyCode == 40) {//光标键移动上,下
processKeyUpAndDown(keyCode);
} else if (keyCode == 13) {// 回车键
processEnter();
}
}
function processAjaxRequest() {
var param = $("#auto_txt").val();
if (param != "") {
ajaxGet(getPolygon_api_auto, "name=" + param, processAjaxResponse);
// getPolygon_api_auto:代表url;"name=" + param:代表参数;processAjaxResponse:回调函数
}
}
// data返回的是json数据
function processAjaxResponse(data) {
$('#auto_div').html("").show();
for (var i = 0; i < data.length; i++) {
var word_div = $("
");word_div.html(data[i].name);
word_div.hover(fnOver, fnOut);
word_div.click(getAutoText);
$('#auto_div').append(word_div);
}
}
function fnOver() {
changeToWhite();
$(this).css('background-color', 'pink');
highLightIndex = $(this).index();
}
function fnOut() {
$(this).css('background-color', 'white');
}
function getAutoText() {
if (highLightIndex != -1) {
$('#auto_txt').val($(this).html());
$('#auto_div').html('').hide();
}
}
function processEnter() {
if (highLightIndex != -1) {
$('#auto_txt').val($('#auto_div').children().eq(highLightIndex).html());
$('#auto_div').html('').hide();
}
}
function processKeyUpAndDown(keyCode) {
var words = $('#auto_div').children();
var num = words.length;
if (num <= 0) return;
changeToWhite();
highLightIndex = ((keyCode != 38 ? num + 1 : num - 1) + highLightIndex) % num;
words.eq(highLightIndex).css('background-color', 'pink');
$('#auto_txt').val(words.eq(highLightIndex).html());
}
function changeToWhite() {
if (highLightIndex != -1) {
$('#auto_div').children().eq(highLightIndex).css('background-color', 'white');
}
}
图片:
要引进jquery的核心js
后台我用play framework返回的json数据