当前位置: 代码迷 >> Web前端 >> 上拉提示框
  详细解决方案

上拉提示框

热度:190   发布时间:2012-10-28 09:54:44.0
下拉提示框

<html>
<head>
<title>Autosuggest Example</title>
<script type="text/javascript">
var arrCities=["北京","上海","合肥","南京","哈尔滨","乌鲁木齐","广州","重庆","深圳",
"大连","呼和浩特","长春","西安","沈阳","杭州","香港","台北","澳门",
"齐齐哈尔","安庆","成都","南昌","无锡","苏州","郑州","石家庄","长沙",
"南宁","福州","拉萨","昆明","大庆","武汉"];
arrCities.sort();
//控制是否显示层div1,bFlag为true则表示显示div1,为false则把div1从页面流里移除
function showDiv1(bFlag){
var oDiv=document.getElementById("div1");
if(bFlag){
oDiv.style.display="block";
}
else{
oDiv.style.display="none";
}
};
//给sel1添加option
function addOption(oListbox,sText){
var oOption=document.createElement("option");
oOption.appendChild(document.createTextNode(sText));
oListbox.appendChild(oOption);
};
//移除一个option
function removeOption(oListbox,iIndex){
oListbox.remove(iIndex);
};
//移除所有的option
function clearOptions(oListbox){
for(var i=oListbox.options.length-1;i>=0;i--){
removeOption(oListbox,i);
}
};
//设置select里的第一个option被选中
function setFirstSelected(oListbox){
if(oListbox.options.length>0){
oListbox.options[0].selected=true;
}
}
//获取匹配的字段
function getAutosuggestMatches(sText,arrValues){
var arrResult=new Array;
if(sText!=""){
for(var i=0;i<arrValues.length;i++){
if(arrValues[i].indexOf(sText)==0){
arrResult.push(arrValues[i]);
}
}
}
else{
showDiv1(false);
}
return arrResult;
};
//把匹配的字段添加到sel1中
function addSuggestOptions(oTextbox,arrValues,sListboxId,oEvent){
var oListbox=document.getElementById(sListboxId);
clearOptions(oListbox);
var arrMatches=getAutosuggestMatches(oTextbox.value,arrValues);
if(arrMatches.length>0){
showDiv1(true);
for(var i=0;i<arrMatches.length;i++){
addOption(oListbox,arrMatches[i]);
}
setFirstSelected(oListbox);
if(oEvent.keyCode==8){
oTextbox.focus();
}
else{
oListbox.focus();
}
}
};
//获取select里的option到textbox
function getSuggestText(oListbox,sTextboxId){
var oTextbox=document.getElementById(sTextboxId);
if(oListbox.selectedIndex>-1){

oTextbox.value=oListbox.options[oListbox.selectedIndex].text;
}
oTextbox.focus();
showDiv1(false);
}
//通过Enter键确定选项
function getSuggestText2(oListbox,sTextboxId,oEvent){
if(oEvent.keyCode==13){
getSuggestText(oListbox,sTextboxId);
}
}
</script>
</head>
<body>
<p>请输入一个城市的名字:</p>
<p>
<input type="text" id="txt1" value="" size="27"
onkeyup="addSuggestOptions(this,arrCities,'sel1',event)" /><br />
<div id="div1" style="background-color:white;display:none;">
<select id="sel1" style="width:202px" size="6"
onclick="getSuggestText(this,'txt1')" onkeyup="getSuggestText2(this,'txt1',event)">
</select>
</div>
</p>
</body>
</html>

  相关解决方案