利用js實現輸入框動態提示信息

http://blog.csdn.net/linzhiqiang0316/article/details/51969040

爲了提高和用戶的交互性,現在的輸入框往往都採用輸入信息自動提示的功能,類似於百度輸入框中的提示功能。

設計思路是:在輸入框input的組件下面放置一個div,這個div主要是爲了提示信息的展示功能,類似於下拉框那種形式。

步驟一:在網頁加載的時候會首先把輸入框中要查詢的信息全部加載出來,並且放置在一個全局變量中。

步驟二:當用戶在輸入框中輸入信息的時候會觸發響應函數,函數的主要功能是獲取用戶的輸入值並繼續監控用戶後續的輸入值,然後把輸入值進行處理,於緩存中的全局變量進行對比操作,把緩存中相同的部分返回給上面提到過的div,div中就顯示了和用戶輸入條件相類似的信息,提供用戶選擇。

步驟三:用戶在菜單中選擇自己想要的信息,通過js代碼實現將選擇的信息返回到輸入框中去。

大體的設計思路就是這樣,現在看看具體的例子:

1.菜單顯示的樣式信息:

[html] view plain copy
.auto_hidden {
width:204px;
border-top: 1px solid #333;
border-bottom: 1px solid #333;
border-left: 1px solid #333;
border-right: 1px solid #333;
position:absolute;
display:none;
}
.auto_show {
width:204px;
border-top: 1px solid #333;
border-bottom: 1px solid #333;
border-left: 1px solid #333;
border-right: 1px solid #333;
position:absolute;
z-index:9999; /* 保證頁面在最前端*/
display:block;
height:100px;
overflow:auto
}
.auto_onmouseover{
color:#ffffff;
background-color:highlight;
width:100%;
}
.auto_onmouseout{
color:#000000;
width:100%;
background-color:#ffffff;
}
2.js部分的處理代碼:
[html] view plain copy
var Bind = function(object, fun) {
return function() {
return fun.apply(object, arguments);
}
}
function AutoComplete(obj,autoObj,arr){
this.obj=document.getElementById(obj); //輸入框
this.autoObj=document.getElementById(autoObj);//DIV的根節點
this.value_arr=arr; //不要包含重複值
this.index=-1; //當前選中的DIV的索引
this.search_value=”“; //保存當前搜索的字符
}
AutoComplete.prototype={
//初始化DIV的位置
init: function(){
this.autoObj.style.left = this.obj.offsetLeft + “px”;
this.autoObj.style.top = this.obj.offsetTop + this.obj.offsetHeight + “px”;
this.autoObj.style.width= this.obj.offsetWidth - 2 + “px”;//減去邊框的長度2px
},
//刪除自動完成需要的所有DIV
deleteDIV: function(){
while(this.autoObj.hasChildNodes()){
this.autoObj.removeChild(this.autoObj.firstChild);
}
this.autoObj.className=”auto_hidden”;
},
//設置值
setValue: function(_this){
return function(){
_this.obj.value=this.seq;
_this.autoObj.className=”auto_hidden”;
}
},
//模擬鼠標移動至DIV時,DIV高亮
autoOnmouseover: function(_this,_div_index){
return function(){
_this.index=_div_index;
var length = _this.autoObj.children.length;
for(var j=0;j

發佈了124 篇原創文章 · 獲贊 16 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章