<分区>
我正在尝试实现类似于 Google 新闻的搜索框。基本上,当您键入搜索词时,您会在下拉列表中看到两个选项,以允许您在新闻或整个网络中进行搜索。
我知道有很多选择插件,例如 select2,但我真的不认为它们是正确的解决方案,因为它们是为选择选项而设计的。
如果有人能在我提出一些 hacky 之前阐明我的方向并指出正确的方向,我将不胜感激。谢谢!
最佳答案
好吧,它是一个小的 jquery 工作,这里不需要插件就是代码。
只需创建一个文本框和一个包含两行的 div,它们将在输入单击时显示,然后使用文本框中的文本更改更改该 li 的文本,结果如下:http://codepen.io/yudircks/pen/Raxabd .
下面是使用的代码
HTML
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<div class="search_cont">
<input type="text">
<div class="result_optins">
<ul>
<li><span></span>-Search news</li>
<li><span></span>-Search the web</li>
</ul>
</div>
</div>
CSS
*{
box-sizing:border-box;
}
body{
font-family:arial;
}
.search_cont input{
width:300px;
height:30px;
padding:10px;
}
.search_cont .result_optins{
width:300px;
display:none;
}
.search_cont .result_optins ul{
padding:0;
margin:0;
}
.search_cont .result_optins ul li{
list-style:none;
padding:5px;
border:1px solid #999;
color:#aaa;
}
.search_cont .result_optins ul li span{
color:#777
}
JQUERY
$(document).ready(function(){
$('input').on('click', function(e){
e.stopPropagation();
$('.result_optins').show();
});
$('.result_optins').on('click', function(e){
e.stopPropagation();
})
$('input').on('input propertychange', function(e){
var inputVal = $(this).val();
$('.result_optins ul li').each(function(){
$(this).find('span').text(inputVal);
})
});
$(document).on('click', function(){
$('.result_optins').hide();
})
})
关于javascript - 如何实现类似谷歌新闻的搜索框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36468704/