javascript - 在隐藏要搜索的列表时创建一个工作搜索栏
问题描述
我想为我的 HTML/CSS/JS 项目创建一个工作搜索栏。我想要做的是隐藏带有搜索选项的列表,但仍然可以在那里搜索东西。我正在使用 W3 学校的模板。这是代码。
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
#myInput {
background-image: url('/css/searchicon.png'); /* Add a search icon to input */
background-position: 10px 12px; /* Position the search icon */
background-repeat: no-repeat; /* Do not repeat the icon image */
width: 100%; /* Full-width */
font-size: 16px; /* Increase font-size */
padding: 12px 20px 12px 40px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
}
#myUL {
/* Remove default list styling */
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd; /* Add a border to all links */
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6; /* Grey background color */
padding: 12px; /* Add some padding */
text-decoration: none; /* Remove default text underline */
font-size: 18px; /* Increase the font-size */
color: black; /* Add a black text color */
display: block; /* Make it into a block element to fill the whole list */
}
#myUL li a:hover:not(.header) {
background-color: #eee; /* Add a hover effect to all links, except for headers */
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<ul id="myUL">
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul>
IE,我想隐藏名称,但仍然可以搜索它们。如果有人可以帮助我,那将不胜感激,在此先感谢!
解决方案
在css中添加这个
#myUL li {
display: none;
}
并更改js功能
function myFunction() {
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "block";
} else {
li[i].style.display = "none";
}
}
}
推荐阅读
- google-cloud-platform - 每次为 VM 分配新 IP
- node.js - 如何使用 axios 向需要参数的路由发送请求?
- expo - 我无法建立 expo-cli
- java - 如何根据屏幕尺寸重新计算变量?
- python - 尽管 URL 带有 urls.py,但无法修复 Django NoReverseMatch 错误
- substrate - 之前区块的存储访问:即 storage::get(&key, &block)
- ruby-on-rails - 我在使用范围方法吗?
- firebase - 计划的 Firebase 云函数的首次运行
- raspberry-pi - 如何在 Raspberry OS 上安装 Spyder 4 IDE
- c# - 无法打开 sqlite 数据库,因为来自 Nuget 的 System.Data.SQLite 在 WinForms 软件中更新到版本 1.0.113.6