DIV CSS 佈局教程網

用 DWR 打造 Google 風格搜尋建議:實作原理與完整程式碼
編輯:關於JavaScript     

本文示範如何用 DWR 做出一個類似 Google 首頁的搜尋關鍵字提示:使用者打字時,後台即時回傳相似關鍵字,以浮層列表呈現,並支援上下鍵選擇、Enter 確認、滑鼠移入高亮。

可設定參數

// 選中 / 未選中的背景色、列表框邊框
var selectedBgColor   = "#CCCCCC";
var unselectedBgColor = "#FFFFFF";
var listBorder        = "1 solid #000000";

內部狀態變數

var oldKeyValue;          // 上次查詢的關鍵字,相同就不重送請求
var mouseLocation = 0;    // 0:滑鼠在提示框外 1:在提示框內
var selectedKeyIndex = -1;// 目前選中的索引,-1 代表無
var oldSelectedKeyIndex = -1;
var tdCount = 0;          // 提示項總數

核心函式

// 為 String 擴充 trim
String.prototype.trim = function() {
  var m = this.match(/^\s*(\S+(\s+\S+)*)\s*$/);
  return (m == null) ? "" : m[1];
};

function initKeyListState(){
  selectedKeyIndex = oldSelectedKeyIndex = -1;
  tdCount = 0;
}

// 把上一次高亮的項目還原
function disSelectedOldKey(){
  if (oldSelectedKeyIndex != -1 && oldSelectedKeyIndex != selectedKeyIndex){
    $('keyId' + oldSelectedKeyIndex).bgColor = unselectedBgColor;
  }
  oldSelectedKeyIndex = selectedKeyIndex;
}

// 上下鍵切換、Enter 填入
function setSelectedKey(){
  if (!$('keyId0')) return;   // 沒有提示項就不處理
  if (event.keyCode == 38){       // 上
    selectedKeyIndex = (selectedKeyIndex == -1)
      ? tdCount - 1
      : (selectedKeyIndex + tdCount - 1) % tdCount;
    $('keyId' + selectedKeyIndex).bgColor = selectedBgColor;
    disSelectedOldKey();
  } else if (event.keyCode == 40){ // 下
    selectedKeyIndex = (selectedKeyIndex == -1)
      ? 0
      : (selectedKeyIndex + 1) % tdCount;
    $('keyId' + selectedKeyIndex).bgColor = selectedBgColor;
    disSelectedOldKey();
  } else if (event.keyCode == 13){ // Enter
    $('cond').value = $('keyId' + selectedKeyIndex).innerText;
    setCursorLast($('cond'));
    $('dropdownlistDiv').style.display = 'none';
  }
}

// 送出查詢
function getConformKey(){
  var keyValue = $('cond').value.trim();
  if (keyValue == oldKeyValue) return;   // 內容沒變,不必再打後台
  if (keyValue == ''){
    DWRUtil.removeAllRows('showKeyList');
    setDropListVisible(false);
    initKeyListState();
  } else {
    useraction.findByLike(keyValue, conformKeyCallback);
  }
}

// DWR 回呼:動態產生提示列
function conformKeyCallback(keyList){
  DWRUtil.removeAllRows('showKeyList');
  initKeyListState();
  if (keyList.length > 0){
    DWRUtil.addRows('showKeyList', keyList, cellFuncs, {
      cellCreator: function(options){
        var td = document.createElement("td");
        td.id = 'keyId' + tdCount++;
        td.onmouseover = function(){
          selectedKeyIndex = parseInt(this.id.substring(5));
          this.bgColor = selectedBgColor;
          disSelectedOldKey();
        };
        td.onclick = function(){
          $('cond').value = this.innerText;
          $('cond').focus();
          setCursorLast($('cond'));
          $('dropdownlistDiv').style.display = 'none';
        };
        return td;
      },
      escapeHtml: false
    });
    setDropListVisible(true);
  } else {
    setDropListVisible(false);
  }
}

var cellFuncs = [ function(data){ return data.username; } ];

// 游標移到文字最後
function setCursorLast(inputObj){
  var r = inputObj.createTextRange();
  r.collapse(true);
  r.moveStart('character', inputObj.value.length);
  r.select();
}

// 建立提示浮層
function createShowDiv(){
  var showDiv = document.createElement("div");
  showDiv.id = "dropdownlistDiv";
  with (showDiv.style){
    position = "absolute";
    left  = parseInt($('cond').style.left.replace('px','')) + 190;
    top   = parseInt($('cond').style.top.replace('px',''))
          + parseInt($('cond').style.height.replace('px','')) + 28;
    width = parseInt($('cond').style.width.replace('px',''));
    border = listBorder;
    zIndex = "1";
    display = 'none';
    backgroundColor = unselectedBgColor;
  }
  showDiv.onmouseover = function(){ mouseLocation = 1; };
  showDiv.onmouseout  = function(){ mouseLocation = 0; };
  showDiv.innerHTML =
    "<div style='width:100%;height:150px;overflow:auto;'>" +
    "<table border='0' style='width:100%;height:20%;font-size:12px;color:#33CC00;'>" +
    "<tbody id='showKeyList'></tbody></table></div>";
  document.body.appendChild(showDiv);
  initKeyListState();
}

function setDropListVisible(isDisplay){
  if (mouseLocation == 1) return;   // 滑鼠還在浮層上,不要收掉
  if ($('cond').value.trim() != '' && isDisplay == true){
    $('dropdownlistDiv').style.display = '';
  } else {
    $('dropdownlistDiv').style.display = 'none';
  }
}

// 掛到 onload(相容不同瀏覽器)
if (window.addEventListener){
  window.addEventListener('load', createShowDiv, false);
} else if (window.attachEvent){
  window.attachEvent('onload', createShowDiv);
}

頁面端 HTML

這段 JavaScript 可以直接寫進需要此效果的 JSP,也可以另存為獨立 js 檔。

<div style="position:absolute;left:190px;top:25px;">
  <input AUTOCOMPLETE="off" type="text" name="cond" id="cond" value="找人"
    style="width:300px;height:23px;z-index:10;top:0;left:0;"
    onkeydown="oldKeyValue=this.value.trim();setSelectedKey();"
    onkeyup="getConformKey();"
    onfocus="if(this.value=='找人') this.value='';setDropListVisible(true);"
    onblur="setDropListVisible(false);" />
  <input type="button" class="btn" value="搜一下" onclick="findBylike();" />
</div>

後端只需一個方法

useraction.findByLike(String name) 是 DAO 層的查詢方法,回傳一個 List。把它換成你自己的實作即可,DWR 會負責把 Java 集合序列化後交給 conformKeyCallback。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved