This is what I'd do: toggle a class on the parent container when matching search elements are detected, and remove the class when there are no matches, or when the input is empty.(这就是我要做的:检测到匹配的搜索元素时在父容器上切换一个类,并在没有匹配项或输入为空时删除该类。)
When the parent class is active, highlight all .searched
children, and hide all non- .searched
children:(当父类处于活动状态时,突出显示所有.searched
子级,并隐藏所有非.searched
子级:)
const container = document.querySelector('.notes'); const notes = [...container.children]; const input = document.querySelector('input'); input.addEventListener('keydown', () => { // Wait for the input field to contain its final value: setTimeout(checkInput); }); const checkInput = () => { const value = input.value.toLowerCase(); const matchingNotes = notes.filter(note => note.textContent.toLowerCase().includes(value)); if (!value || matchingNotes.length === 0) { container.classList.remove('searchActive'); return; } container.classList.add('searchActive'); for (const note of notes) { if (matchingNotes.includes(note)) { note.classList.add('searched'); } else { note.classList.remove('searched'); } } }
.searchActive > .searched { background-color: yellow; } .searchActive > *:not(.searched) { display: none; }
<div class="notes"> <div>FIRST NOTE</div> <div>SECOND NOTE</div> <div>THIRD NOTE</div> <div>THIRDDD NOTE</div> <div>THIRL NOTE</div> </div> <div> <input type="text" placeholder="Search..."> </div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…