最近在做一个憑證相關的系統,其中幾個輸入框需要聯想功能。在 Ajax 的吸引下我找到了 Microsoft 的 ASP.NET 2.0 Ajax Extensions 1.0,它是基於 .NET Framework 2.0 開發的,正好符合需求,於是就用 AutoCompleteExtender 來實作。
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="1"
CompletionInterval="300"
EnableCaching="true"
CompletionSetCount="10"
BehaviorID="AutoCompleteEx" runat="server" ServiceMethod="GetCompletionList"
UseContextKey="True" TargetControlID="TextBox1">
<Animations>
<OnShow>
<Sequence>
<OpacityAction Opacity="0" />
<HideAction Visible="true" />
<ScriptAction Script="
// Cache the size and setup the initial size
var behavior = $find('AutoCompleteEx');
if (!behavior._height) {
var target = behavior.get_completionList();
behavior._height = target.offsetHeight - 2;
target.style.height = '0px';
}" />
<Parallel Duration=".1">
<FadeIn />
<Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx')._height" />
</Parallel>
</Sequence>
</OnShow>
<OnHide>
<Parallel Duration=".1">
<FadeOut />
<Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx')._height" EndValue="0" />
</Parallel>
</OnHide>
</Animations>
</cc1:AutoCompleteExtender>
</div>
實作過程中遇到一個惱人的行為:頁面裡只有一個 TextBox 且沒有其他送出鈕時,瀏覽器會把 Enter 當成表單送出,畫面直接刷新。解法是在表單中補一個隱藏的送出鈕,並把表單的 onsubmit 攔下來:
<script type="text/Javascript">
// Work around browser behavior of "auto-submitting" simple forms
var frm = document.getElementById("ASPnetForm");
if (frm) {
frm.onsubmit = function() { return false; };
}
</script>
<input type="submit" style="display:none;" />
動畫部分用 OnShow/OnHide 做了淡入淡出加上高度展開的效果,做法是先記下建議清單的實際高度,再從 0 開始長到目標高度;關閉時反向操作。這樣比直接顯示/隱藏自然得多。