ajax 智能搜索
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Search.ascx.cs" Inherits="UserControls_Search" %>
<style>
#search_suggest
{
position:absolute;
background:#FFFFFF;
text-align:left;
border:1px #000000 solid;
cursor:pointer;
display:none;
z-index:10;
width:251px;
}
.suggest_link_over
{
background-color:#e8f2fe;
padding:2px 6px;
font-weight:bold;
color:red;
cursor:pointer;
display:block;
}
.suggest_link
{
padding:2px 6px;
background-color:#FFFFFF;
}
</style>
<script language="javascript" type="text/javascript">
//创建Aajx对象
function createXmlHttpRequest() {
var xmlhttp = null;
try {
xmlhttp = XMLHttpRequest();
} catch (e1) {
try {
xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
} catch (e2) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e3) {
xmlhttp = false;
alert("创建失败!");
}
}
}
return xmlhttp;
}
var xmlHttp = createXmlHttpRequest();
//删除字符串前后空白
function Trim(strToString)
{
return strToString.replace(/^\s\s*/,'').replace(/\s\s*$/,'');
}
//输入框发生变化时
function change_key(){
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
var str = Trim(escape(document.getElementById("keyword").value));
if (str!=''){
xmlHttp.open("get", "AjaxSearch.aspx?key=" + str, true);
xmlHttp.onreadystatechange = handSearchRequest;
xmlHttp.send(null);
}
}
}
//接收对象,并从"|"分隔
function handSearchRequest(){
if (xmlHttp.readyState == 4){
var div = document.getElementById("search_suggest");
div.innerHTML = "";
var str = xmlHttp.responseText.split("|");
$("search_suggest").innerHTML="";
for (var i=0; i<str.length; i++){
var suggest = '<div onmouseover="javascript:suggestOver(this);"';
suggest +=' onmouseout="javascript:suggestOut(this);"';
suggest += ' onclick="javascript:setSearch(this.innerHTML);"';
suggest +=' class="suggest_link">' + str[i] + '</div>';
$("search_suggest").innerHTML += suggest;
}
$("search_suggest").style.display="block";
$("search_suggest").innerHTML +="<div class='c' onclick='c_close()'>Close It</div>";
Mka_1();
}
}
//关闭录入框
function c_close(){
$("search_suggest").style.display="none";
}
function Mka_1(){
e = $("keyword");
var t=e.offsetTop;
var l=e.offsetLeft;
while(e=e.offsetParent){
t+=e.offsetTop;
l+=e.offsetLeft;
}
$("search_suggest").style.top=t+20;
$("search_suggest").style.left=l;
}
function $(d)
{
return document.getElementById(d);
}
function setSearch(div_value){
document.getElementById("keyword").value = div_value;
$("search_suggest").style.display="none";
}
function suggestOver(div_value){
div_value.className ='suggest_link_over';
}
function suggestOut(div_value){
div_value.className ='suggest_link';
}
function b_hide()
{
//$("search_suggest").style.display="none";
}
</script>
<div id="sp" style=" margin-left:20px;">
<input name="keyword" type="text" class="srchTxt" id="keyword" value="" size="35" maxlength="256" autocomplete="off" onkeyup="change_key()" onblur="b_hide()"/>
<input type="image" name="imageField" src="http://images.cnblogs.com/search.gif" />
<div id="search_suggest"></div>
</div>