JavaScript 自动完成功能实现

Web开发中,自动完成功能是一种常见的用户交互方式,它能够根据用户输入的部分信息,自动提供可能的完整信息供用户选择。这种功能可以大大提高用户输入的效率和体验。本文将介绍如何使用JavaScript和ASP Classic实现自动完成功能。

首先,需要创建一个HTML输入框,用于接收用户的输入。同时,还需要一个用于显示建议列表的容器。以下是HTML结构的示例:

<input type="text" id="txtSearchEngines" class="data"> <div id="suggestionBox" style="display:none"></div>

接下来,需要定义一些CSS样式,以美化建议列表的外观。

#suggestionBox { position: absolute; z-index: 999; border: 1px gray solid; background-color: #E6E6E6; width: 300px; } .suggest-data { line-height: 20px; font-family: Tahoma; font-size: 12px; } .rowSelected { background-color: #415C7C; color: white; }

然后,需要编写JavaScript代码来实现自动完成的逻辑。首先,需要绑定事件监听器,以便在用户输入时触发相应的操作。

var xmlhttp, rowToSelect = 0, searchTextBox = document.getElementById("txtSearchEngines"), _URL = "AutoSuggest.asp"; BindSearchTextBox(); function BindSearchTextBox() { searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox, false); searchTextBox.addEventListener("keydown", HandleTabKey); document.getElementsByTagName("body")[0].addEventListener("click", CloseSuggestionBox); }

在用户输入时,需要根据输入的内容向服务器发送请求,并获取建议列表。以下是发送请求和显示建议的代码示例:

function KeyUpOnSearchTextBox(e) { var suggestBox = document.getElementById("suggestionBox"); if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 8)) { searchTextBox.removeEventListener("keyup", KeyUpOnSearchTextBox); if((e.keyCode == 40 || e.keyCode == 38) && suggestBox.style.display != "none") { SelectSuggestedRow(e.keyCode == 40 ? 1 : -1); BindSearchTextBox(); } else { if(null != searchTextBox.value && "" != searchTextBox.value) SendAJAXRequestToServer(_URL + "?type=s&searchKey=" + searchTextBox.value, ShowSuggestion, true); else { HideSuggestionBox(); BindSearchTextBox(); } } } else if(e.keyCode == 13) { searchTextBox.removeEventListener("keyup", KeyUpOnSearchTextBox); GetSelectedDetail(); } } function ShowSuggestion() { if(xmlhttp.readyState == 4) { if(xmlhttp.responseText != "") { var suggestBox = document.getElementById("suggestionBox"), suggestRow = document.getElementById("suggest-rows"); suggestBox.style.display = ""; suggestBox.style.top = searchTextBox.offsetTop + searchTextBox.offsetHeight + 2; suggestBox.style.left = searchTextBox.offsetLeft; suggestBox.innerHTML = xmlhttp.responseText; suggestBox.style.display = ""; SelectSuggestedRow(0); } else HideSuggestionBox(); BindSearchTextBox(); } } <%@ Language=VBScript %> <% Option Explicit %> <% 'put your security/authenciation code here Response.Write GetSuggestion Response.End Function GetSuggestion() Dim searchKey searchKey = Request.QueryString("searchKey") If searchKey = "g" Then GetSuggestion = _ "" & _ "" & _ "" & _ "" & _ "
Google
Google2
" ElseIf searchKey = "b" Then GetSuggestion = _ "" & _ "" & _ "
Bing
" End If End Function %>
沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485