html:
<table>
<tr>
<td>
输入项
</td>
<td>
<input type="text" name="input_data" id="input_data" value="" autocomplete="off" onkeyup="show_list('search_data');" onblur="hide_sugg()" />
<div class="suggestions_box" id="suggestions" style="display: none;">
<div class="suggestion_list" id="auto_suggestions_list"></div>
</div>
</td>
</tr>
</table>
js:
function show_list(url) {
var input_data = $("#input_data").val();
if(input_data == "" || input_data == null){
return null;
} else {
$.ajax( {
type : "post",
url : "/" + url,
data : "input_data=" + input_data,
dataType : 'json',
success : function(res) {
if (res.length > 0) {
$('#suggestions').show();
$("#auto_suggestions_list").html("");
for (i = 0; i < res.length; i++) {
var span_dom = $('<li onClick="fill('+"\'"+res[i]+"\'"+')"/>').text(res[i]);
$('#auto_suggestions_list').append(span_dom);
}
} else {
$("#auto_suggestions_list").html("");
$('#suggestions').hide();
}
}
});
}
}
function fill(value) {
$("#input_data").val(value);
$("#input_data").focus();
setTimeout("$('#suggestions').hide();", 200);
}
function hide_sugg() {
$("body").not("#suggestions").not("#auto_suggestions_list").not("#auto_suggestions_list li").click(function(){
setTimeout("$('#suggestions').hide();", 200);
});
$("body").keyup(function(event){
var key = event.which;
if (key == 9 || key == 13){
setTimeout("$('#suggestions').hide();", 200);
}
});
}
后台php:
public function search_data(){
...
echo json_encode($data);
}
css:
.suggestions_box {
position: relative;
width: 230px;
z-index: 998;
}
.suggestion_list {
background: none repeat scroll 0 0 white;
border: 1px solid #B8CFDB;
position: absolute;
width: 230px;
z-index: 999;
height: expression( this.scrollHeight > 200 ? "200px" : "auto" );
max-height: 200px;
overflow-y: auto;
}
.suggestion_list li{
padding: 3px;
cursor: default;
list-style-type :none;
}
.suggestion_list li:hover {
background-color: #EEEEEE;
}