多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[toc] ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin:0; padding:0; } input{ display:block; outline:none; } a{ display:block; text-decoration:none; color:#000; } a:hover,a:active,a:target{ text-decoration:none; color:#000 } ul,li{ list-style:none; } html,body{ width:100%; height:100%; border-top:1px solid transparent; } .box{ margin:20px auto; width:500px; } .box input{ padding:0 10px; width:300px; height:35px; border:1px solid #008000; } .box ul { display:none; position: relative; top:-1px; border:1px solid #008000; } .box ul li,.box ul li a{ height:35px; line-height:35px; } .box ul li a{ padding:0 10px; } .box ul li a:hover{ background:#ccc; } </style> </head> <body> <div class="box"> <input type="text" id="searchInput"> <ul id="searchList"> <li><a href="javascript:;">ahhh-front</a></li> <li><a href="javscript:;">ahhh-nodejs</a></li> <li><a href="javscript:;">ahhh-html5</a></li> <li><a href="javscript:;">ahhh-css3</a></li> <li><a href="javscript:;">ahhh-who says</a></li> </ul> </div> <script> //什么时候显示: //1)文本框获取焦点,并且文本框中有内容的时候 ///2)在文本框操作内容的的时候(新输入/删除),如果内容没有清空,我们就显示,否则就隐藏 //->隐藏 //1)点击页面中其余的位置(除了文本框和searchList里面的每一行)都隐藏 //2)点击searchList中的列表隐藏,但是还要把列表中的内容放到文本框中 //->不管是获取焦点onfocus,还是再里面编辑内容onkeyup,都是有内容显示,没内容隐藏 var searchInput = document.getElementById("searchInput") ,searchList = document.getElementById("searchList"); searchInput.onfocus = searchInput.onkeyup = function(e){ console.log(1); var val = this.value.replace(/(^ +| +$)/g,""); //获取文本框中的内容,并且去除它的首尾空格 searchList.style.display = val.length>0?"block":"none"; } document.body.onclick = function(e){ e = e || window.event; e.target = e.target || e.srcElement; //->如果事件源是searchList下的a,我们让searchList隐藏,并且把当前点击这个a中的内容放到文本框中 if(e.target.tagName.toLowerCase()==='a'&&e.target.parentNode.parentNode.id==="searchList"){ searchInput.value = e.target.innerHTML; searchList.style.display = "none"; return; } // if(e.target.id === 'searchInput'){ // return; // } //或则在input中阻止冒泡 searchList.style.display = "none"; } //->我们可以阻止一个容器中某些特殊性的元素,让其不再委托的范围内 searchInput.onclick = function(e){ e = e || window.event; e.stopPropagation?e.stopPropagation():e.cancelBubble = true; } </script> </body> </html> ```