实现输入自动补全:输入字符前隐藏搜索列表项
解决方案:输入前隐藏搜索列表
没问题,我帮你搞定这个需求!你要的是输入至少1个字符前完全隐藏搜索列表,而不是默认显示所有项,这个其实只需要在现有代码基础上做两处小修改就行,很简单~
修改思路
- 先让列表默认隐藏,确保页面加载时不会显示所有选项
- 在搜索函数里判断输入内容长度:为空则继续隐藏列表;有内容时先显示列表,再执行过滤逻辑
修改后的完整代码
CSS 部分
* { box-sizing: border-box; } #myInput { background-image: url('/css/searchicon.png'); background-position: 10px 12px; background-repeat: no-repeat; width: 94%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myUL { list-style-type: none; padding: 0; margin: 0; display: none; /* 新增:默认隐藏列表 */ } #myUL li a { border: 1px solid #ddd; margin-top: -1px; /* 避免重复边框 */ background-color: #f6f6f6; padding: 12px; text-decoration: none; font-size: 14px; color: black; display: block } #myUL li a:hover:not(.header) { background-color: #eee; }
JavaScript 部分
function myFunction() { var input, filter, ul, li, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); // 新增:判断输入内容长度 if (filter.length === 0) { ul.style.display = 'none'; // 输入为空时隐藏列表 return; // 直接结束函数,无需执行后续过滤 } else { ul.style.display = 'block'; // 有输入时显示列表 } // 原有过滤逻辑 for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } }
HTML 部分(无需修改,直接沿用)
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search " title="Type in a name"> <ul id="myUL"> <li><a href="#" target="_blank" rel="external nofollow">test 1</a></li> <li><a href="#" target="_blank" rel="external nofollow">test 2</a></li> <li><a href="#" target="_blank" rel="external nofollow">test 3</a></li> <li><a href="#" target="_blank" rel="external nofollow">test 4</a></li> <li><a href="#" target="_blank" rel="external nofollow">test 5</a></li> <li><a href="#" target="_blank" rel="external nofollow">test 5.5</a></li> </ul>
效果说明
- 页面加载完成后,搜索列表会完全隐藏
- 当你在输入框输入至少1个字符时,列表会自动显示,并实时过滤匹配项
- 清空输入框时,列表会再次隐藏
内容的提问来源于stack exchange,提问作者Yesufu
相关产品推荐
相关产品推荐

