如何利用JS仿做百度搜索框
导读:在实际案例的操作过程中,我们可能会遇到“如何利用JS仿做百度搜索框”这样的问题,那么我们该如何处理和解决这样的情况呢?这篇小编就给大家总结了一些方法,具有一定的借鉴价值,希望对大家有所帮助,接下来就让小编带领大家一起了解看看吧。...
在实际案例的操作过程中,我们可能会遇到“如何利用JS仿做百度搜索框”这样的问题,那么我们该如何处理和解决这样的情况呢?这篇小编就给大家总结了一些方法,具有一定的借鉴价值,希望对大家有所帮助,接下来就让小编带领大家一起了解看看吧。
本文实例为大家分享了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仿做百度搜索框”的文章就介绍到这了,感谢各位的阅读,更多相关如何利用JS仿做百度搜索框内容,欢迎关注网络资讯频道,小编将为大家输出更多高质量的实用文章!
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 如何利用JS仿做百度搜索框
本文地址: https://pptw.com/jishu/655066.html
