用Vanilla JavaScript进行页面内过滤搜索
If you have a page that includes a lot of information, it’s a good idea to let users search for what they might be looking for. I’m not talking about searching a database or even searching JSON data — I’m talking about literally searching text on a single rendered web page. Users can already use the built-in browser search for this, but we can augment that by offering our own search functionality that filters down the page making matching results easier to find and read.
如果你有一个包含大量信息的页面,让用户搜索他们可能要找的东西是个好主意。我说的不是搜索数据库,甚至不是搜索JSON数据--我说的是在单个渲染的网页上搜索文本。用户已经可以使用内置的浏览器搜索,但我们可以通过提供我们自己的搜索功能来增强这一功能,在页面上进行过滤,使匹配的结果更容易找到和阅读。
Here’s a live demo of what we’re going to build:
下面是我们要建立的一个现场演示。
I use this same technique on my real project: https://freestuff.dev/.
我在我的真实项目中也使用了这种技术:https://freestuff.dev/。
Meet JavaScript!
认识一下JavaScript!
Well, you might know JavaScript already. JavaScript is going to handle all the interactivity in this journey. It’s going to…
好吧,你可能已经知道了JavaScript。JavaScript将处理这个旅程中的所有互动性。它将会...
- find all the content we want to search through,
- 找到我们想要搜索的所有内容。
- watch what a user types in the search input,
- 观察用户在搜索输入中输入的内容。
- filter the
innerText
of the searchable elements, - 过滤可搜索元素的
innerText
。 - test if the text includes the search term (
.includes()
is the heavy lifter here!), and - 测试文本是否包括搜索词(
.includes()
是这里的重头戏!),以及 - toggle the visibility of the (parent) elements, depending on if they include the search term or not.
- 切换(父)元素的可见性,取决于它们是否包括搜索词。
Alright, we have our requirements! Let’s start working.
好了,我们有了自己的要求!让我们开始工作吧。
The basic markup
基本标记
Let’s assume we have a FAQ page. Each question is a “card” which has a title and content:
让我们假设我们有一个FAQ页面。每个问题都是一个 "卡片",有一个标题和内容。
<h1>FAQ Section</h1> <div class="cards"> <h3>Who are we</h3> <p>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized </p>
</div> <div class="cards"> <h3>What we do</h3> <p>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentiall...