首页 > 编程 > JavaScript > 正文

基于JavaScript实现百度搜索框效果

2019-11-19 16:00:04
字体:
来源:转载
供稿:网友

本文实例为大家分享了js实现百度搜索框展示效果的具体代码,供大家参考,具体内容如下

具体代码如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style>  *{   margin:0;   padding:0;   font-size:14px;  }  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;  }  .box{   position:absolute;   top:20px;   left:50%;   margin-left:-250px;   width:500px;  }  .box input{   width:300px;   height:35px;   padding:0 10px;   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='searchInp'>  <ul id='searchList'>   <li><a href="javascript:;">111111111111</a></li>   <li><a href="javascript:;">2222222222</a></li>   <li><a href="javascript:;">33333333333</a></li>   <li><a href="javascript:;">444444444444</a></li>   <li><a href="javascript:;">5555555555555</a></li>  </ul> </div> <script>  //显示  /*   1、文本框获取焦点,并且文本框中有内容的时候   2、在文本框中操作内容(新输入/删除),如果内容没有清空,我们就显示,否则就隐藏  */  //隐藏  /*   1、点击页面中其余的位置(除了点击文本框和searchList里面的每一行)都隐藏;   2、点击searchList中的列表隐藏,但是还要把列表中的内容放到文本框中  */  //不管是获取焦点onfocus,还是在里面编辑内容onkeyup,都是有内容显示,没内容隐藏  var searchInp = document.getElementById('searchInp'),searchList = document.getElementById('searchList');  searchInp.onkeyup = searchInp.onfocus = function(){   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"){    searchList.style.display = "none";    searchInp.value = e.target.innerHTML;    return;   }   //如果事件源是文本框还需要单独的处理   // if(e.target.id === "searchInp"){   //  return;   // }   searchList.style.display = "none";  }  //我们可以阻止一个容器中某些特殊性的元素,让其不在委托的范围内:我们只需要把这些不需要委托的阻止冒泡传播即可  searchInp.onclick = function(e){   e = e || window.event;   e.stopPropagation ? e.stopPropagation() : e.cancelBubble = "true";  } </script></body></html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表