如何让搜索结果显示的更短,比如4行,而不是全部显示到底部?
这是我的代码:
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
CSS 代码:
#myUL li a {
transform: translate(270px,-1400px);
border: 1px solid #ddd;
margin-top: -1px; /* Prevent double borders */
background-color: #f6f6f6;
width: 28%;
padding: 12px;
text-decoration: none;
font-size: 16px;
color: black;
display: block;
}
其余代码:
var UL = document.getElementById("myUL");
// hilde the list by default
UL.style.display = "none";
var searchBox = document.getElementById("myInput");
// show the list when the input receive focus
searchBox.addEventListener("focus", function(){
// UL.style.display = "block";
});
// hide the list when the input receive focus
searchBox.addEventListener("blur", function(){
});
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
ul = document.getElementById("myUL");
filter = input.value.toUpperCase();
// if the input is empty hide the list
if(filter.trim().length < 1) {
ul.style.display = "none";
return false;
} else {
ul.style.display = "block";
}
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
// This is when you want to find words that contain the search string
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
请帮助我,我现在正在努力解决这个问题 :( 提前致谢!
最佳答案
试试这个
var limit = 4;
for (i = 0, j = 0; i < li.length && j < limit; i++) {
在匹配的 block 中,这个
// This is when you want to find words that contain the search string
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
j++;
} else {
当你进行了 4 次匹配后,循环将终止
关于javascript - 如何使搜索列表更短?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58231769/