DWR實現模擬Google搜索效果實現原理及代碼
2024-05-06 14:19:44
供稿:網友
代碼如下:
<!-- 模擬google搜索 -->
<script type="text/javascript">
/********************************可配置選項********************************/
// 被選中的相似關鍵字背景顏色
var selectedBgColor = "#CCCCCC";
// 未被選中的相似關鍵字背景顏色
var unselectedBgColor = "#FFFFFF";
// 相似關鍵字列表框的邊框
var listBorder = "1 solid #000000";
/***************************************************************************/
/********************************不可配置選項********************************/
// 上一次輸入的關鍵字(用來判斷關鍵字是否有改變,沒有則不再去服務端重新獲取提示關鍵字)
var oldKeyValue;
// 鼠標相對于提示關鍵字列表框的位置(0:提示框外面,1:提示框里面)
var mouseLocation = 0;
// 當前選中的提示關鍵字索引(從0開始,等于-1表示沒有被選中項)
var selectedKeyIndex = -1;
// 上一次選中的提示關鍵字索引(從0開始,等于-1表示沒有上次被選中項)
var oldSelectedKeyIndex = -1;
// 提示關鍵字總數
var tdCount = 0;
/***************************************************************************/
/*
用途:給String對象添加去除左右空格方法
*/
String.prototype.trim = function() {
var m = this.match(/^/s*(/S+(/s+/S+)*)/s*$/);
return (m == null) ? "" : m[1];
}
/*
用途:初始化提示關鍵字列表框的狀態
*/
function initKeyListState(){
selectedKeyIndex = -1;
oldSelectedKeyIndex = -1;
tdCount = 0;
}
/*
用途:將上一次選中的關鍵字項變為未選中
*/
function disSelectedOldKey(){
//判斷說明:oldSelectedKeyIndex!=selectedKeyIndex
// 當只有一個相似關鍵字的時候,則不存在上一次選中和這次選中關鍵字,
// 只要第一次選中后,按向上或向下箭頭都是選中。
if (oldSelectedKeyIndex!=-1&&oldSelectedKeyIndex!=selectedKeyIndex){
$('keyId'+ oldSelectedKeyIndex).bgColor=unselectedBgColor;
}
// 上一次選中項更新
oldSelectedKeyIndex = selectedKeyIndex;
}
/*
用途:當按上下箭頭時選中新的提示關鍵字項,按回車時將選中的提示關鍵字輸入到搜索框。
*/
function setSelectedKey(){
// $('keyId0')存在表示有相關提示關鍵字,不存在則不處理。
if($('keyId0')){
if (event.keyCode==38){
//------處理向上事件------
if (selectedKeyIndex==-1){
selectedKeyIndex = tdCount-1;
}else{
selectedKeyIndex= (selectedKeyIndex+tdCount-1)%tdCount;
}
$('keyId'+ selectedKeyIndex).bgColor= selectedBgColor;
disSelectedOldKey();
}else if (event.keyCode==40){
//------處理向下事件------
if (selectedKeyIndex==-1){
selectedKeyIndex = 0;
}else{
selectedKeyIndex = (selectedKeyIndex+1)%tdCount;
}
$('keyId'+ selectedKeyIndex).bgColor= selectedBgColor;
disSelectedOldKey();