js 实现下拉框的搜索
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <div style="width:200px;height:20px;" > <input type="text" style="width:200px;height:20px;" onclick="myClick();" id="myInput"> </div> <div id="searchdiv" style="display:none;z-index:3; width:200px;height:20px;" onMouseOver="mouseOver()" onMouseOut="mouseOut()"> <input type="text" id="search" onkeyup="mysearch()" style="width:200px;height:20px;"> </div> <div id="checkboxdiv" style="display:none;border:1px solid #A9A9A9;width:200px;z-index:2;overflow-y :scroll;height:100px;background-color:white; " onMouseOver="mouseOver()" onMouseOut="mouseOut()"> </div> </body> </html> <script type="text/javascript"> var array = [{id:1,value:"红色"},{id:2,value:"白色"},{id:3,value:"黑色"}]; var checkboxdiv=document.getElementById("checkboxdiv"); var indiv=false; var search=document.getElementById("search"); var selectId=[]; var selectValues=[]; window.onload=function(){ for(var i=0;i<array.length;i++){ var tmpdiv=document.createElement("div"); var tmpinput=document.createElement("input"); tmpinput.setAttribute("name","mycheckbox"); tmpinput.setAttribute("type","checkbox"); tmpinput.setAttribute("onclick","mycheck(this)"); tmpinput.setAttribute ("value",array[i]["id"]); var tmptext=document.createTextNode(array[i]["value"]); tmpdiv.appendChild(tmpinput); tmpdiv.appendChild(tmptext); checkboxdiv.appendChild(tmpdiv); } document.onclick=function(event){ if(event.target.id=="myInput"||indiv){ return; } checkboxdiv.style.display="none"; document.getElementById("searchdiv").style.display="none"; } }; function myClick(){ document.getElementById("searchdiv").style.display="block"; checkboxdiv.style.display="block"; } function mouseOver(){ indiv=true; } function mouseOut(){ indiv=false; } //checkbox 点击事件 function mycheck(obj){ if(obj.checked){ selectId.push(obj.value); selectValues.push(obj.nextSibling.nodeValue); }else{ for(var i=0;i<selectId.length;i++){ if(selectId[i]==obj.value){ selectId.splice(i,1); selectValues.splice(i,1); } } } console.log(selectValues); document.getElementById("myInput").value=selectValues; } //模糊查询 function mysearch(){ var checkboxlist=document.getElementsByName("mycheckbox"); for(var i=0;i<checkboxlist.length;i++){ if(checkboxlist[i].nextSibling.nodeValue.indexOf(search.value)==-1){ checkboxlist[i].parentNode.style.display="none"; }else{ checkboxlist[i].parentNode.style.display="block"; } } } </script>
111111