欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-01-30 10:24:20|栏目:JavaScript代码|点击:

本文实例为大家分享了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>

上一篇:js不能跳转到上一页面的问题解决方法

栏    目:JavaScript代码

下一篇:JavaScript对象封装的简单实现方法(3种方法)

本文标题:基于JavaScript实现百度搜索框效果

本文地址:http://www.codeinn.net/misctech/53770.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有