如何使用 HTML、CSS 和 JavaScript 构建具有过滤功能的响应式表单

2025-06-07

如何使用 HTML、CSS 和 JavaScript 构建具有过滤功能的响应式表单

大多数以表格形式显示数据列表的网站通常都实现了某种过滤功能。这有助于用户根据他们在表单输入框中输入的文本过滤相关项目。

在这个快速教程中,我们将构建一个响应式可过滤表,如下所示:

响应式表格

该表将包含开发人员列表。每行包含姓名、年龄和编程语言。当用户在输入字段中输入内容时,该表将过滤并返回与输入值匹配的行。

在构建过程中,您将了解一些 CSS 属性以及使用 JavaScript 的 DOM 访问/操作。

您可以从CodePen获取示例代码

入门

您需要在项目文件夹中创建三个简单的文件。它们是用于 HTML 标记的 index.html、用于样式的 style.css 和用于脚本的 index.js。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Filterable Table</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

  <script src="index.js" type="text/javascript"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

确保链接您的样式表和脚本文件,就像我在上面的 HTML 中所做的那样。

表格的 HTML 标记

在 body 标签内添加以下标记:

<div class="app">
    <input type="text" id="searchInput" placeholder="filter developer...">

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
          <th>Language</th>
        </tr>
      </thead>
      <tbody id="names">
        <tr>
          <td>Kingsley</td>
          <td>32</td>
          <td>JavaScript</td>
        </tr>
        <tr>
          <td>Samuel</td>
          <td>22</td>
          <td>Python</td>
        </tr>
        <tr>
          <td>Joyce</td>
          <td>28</td>
          <td>Ruby</td>
        </tr>
        <tr>
          <td>Jake</td>
          <td>29</td>
          <td>Python</td>
        </tr>
        <tr>
          <td>Daniel</td>
          <td>40</td>
          <td>JavaScript</td>
        </tr>
        <tr>
          <td>Mary</td>
          <td>21</td>
          <td>C</td>
        </tr>
        <tr>
          <td>David</td>
          <td>26</td>
          <td>JavaScript</td>
        </tr>
        <tr>
          <td>Kelly</td>
          <td>31</td>
          <td>React</td>
        </tr>
        <tr>
          <td>Cleo</td>
          <td>43</td>
          <td>Java</td>
        </tr>
        <tr>
          <td>Peter</td>
          <td>19</td>
          <td>Vue</td>
        </tr>
        <tr>
          <td>George</td>
          <td>59</td>
          <td>Cobol</td>
        </tr>
        <tr>
          <td>James</td>
          <td>29</td>
          <td>JavaScript</td>
        </tr>
        <tr>
          <td>Ethan</td>
          <td>22</td>
          <td>PHP</td>
        </tr>
        <tr>
          <td>Sandra</td>
          <td>29</td>
          <td>R</td>
        </tr>
        <tr>
          <td>Pires</td>
          <td>34</td>
          <td>React Native</td>
        </tr>
        <tr>
          <td>Martha</td>
          <td>30</td>
          <td>React</td>
        </tr>
      </tbody>
    </table>
  </div>
Enter fullscreen mode Exit fullscreen mode

第一个元素是表单输入框。我们将使用它来收集用户的数据。

然后我们得到一个表格。该表格由表头 ( thead) 和表体 ( tbody) 组成。表头包含一行 ( tr) 数据,即标题。表体包含 16 行数据,每行包含姓名、年龄和编程语言。

我们将这两个元素包裹在一个父 div 标签中。它们将帮助我们对齐,正如我们稍后在 CSS 中看到的那样。

保存文件并在网络浏览器上打开应用程序。

htmltable.png

如何使用 CSS 设置表格样式

现在我们将为表格添加一些样式。首先,我们设置基本样式,如下所示:

@import url("https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap");

/* Set no margin and padding around body. Set height to take up entire screen height. Align everything to the center, both horizontally and vertically */

body {
  margin: 0;
  height: 100vh;
  padding: 0;
  font-family: "lato", sans-seriff;
  display: grid;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}

/* Remove border and outline around input. Set width to take up the entire width of parent and set margin on bottom */

#searchInput {
  border: none;
  outline: none;
  width: 100%;
  margin-bottom: 20px;
}

/* When input gains focus, add a blue border below it */

#searchInput:focus {
  border-bottom: 2px solid #4575b6;
}
Enter fullscreen mode Exit fullscreen mode

表格将与中心对齐。

中心表.png

为了使表格看起来更好,我们可以使用以下样式规则:

/* Sets width of table container (div) to 80% of browser window's width and the height to 100% of window's height. `vh` and `vw` makes the table responsive because it scales along with screen size. Also set margin of 20px to top and bottom */

.app {
  width: 80vw;
  height: 100vh;
  margin: 20px 0;
}

/* Collapse all borders separating each cell. Table takes up entire width of .app. Set gray shadow around table */
table {
  border-collapse: collapse;
  width: 100%;
  box-shadow: 0 5px 7px gray;
}

/* Set shadow on just the table head */
thead {
  box-shadow: 0px 0px 10px gray;
}

/* Add some space around table heading. Align text to right and transform to uppercase */

th {
  padding: 1rem 3rem;
  text-transform: uppercase;
  letter-spacing: 1px;
  text-align: left;
}

/* Add padding on each cell */
td {
  padding: 0.5rem 3rem;
  font-size: 1rem;
}

/* Create alternating color(blue) across the rows. Set blue on all even ones (2, 4, 6 ...) */

tr:nth-child(even) {
  background-color: #dee8f5;
}
Enter fullscreen mode Exit fullscreen mode

现在我们的表格看起来好多了,而且响应也更灵敏了。

响应式表格

如何使用 JavaScript 实现过滤功能

此时表格基本处于静态。我们将使用 JavaScript 实现根据用户在表单字段中输入的内容筛选姓名的逻辑。

在脚本文件中,定义一个名为 filter 的函数。前三行我们访问用户的输入值,将表主体传递<tbody>给变量 names,最后<tr>从 内部访问所有表行<tbody>

我们还将值更改为大写以确保所有内容一致(用户可能会输入“j”而不是“J”)。

  /* This function will check for the user's input and based on that will either hide or display a particular row */

  function filter() {
    // Access text value and elements from the DOM 
    let value = document.getElementById("searchInput").value.toUpperCase();
    let names = document.getElementById("names");
    let rows = names.getElementsByTagName("tr");

   // Code continues
Enter fullscreen mode Exit fullscreen mode

接下来,我们循环遍历每个数组。对于每一行,我们访问最后一列(语言列)并获取其文本内容(实际值)。

for (i = 0; i < rows.length; i++) {
    let column = rows[i].getElementsByTagName("td")[2];
    let language = column.textContent;

    rows[i].style.display =
      language.toUpperCase().indexOf(value) > -1 ? "" : "none";
  }
}

document.getElementById("searchInput").addEventListener("keyup", filter);
Enter fullscreen mode Exit fullscreen mode

循环遍历表格行

如果表中的实际字符串值包含用户输入的任何值,我们就显示该行。否则,我们就隐藏该行。我们还使用了三元运算符来缩短条件语句。

最后,我们在输入上添加一个事件监听器。每次释放按键时,都会调用该过滤器。

以下是完整代码:

function filter() {
  let value = document.getElementById("searchInput").value.toUpperCase();
  var names = document.getElementById("names");
  var rows = names.getElementsByTagName("tr");

  for (i = 0; i < rows.length; i++) {
    let column = rows[i].getElementsByTagName("td")[2];
    let language = column.textContent;

    rows[i].style.display =
      language.toUpperCase().indexOf(value) > -1 ? "" : "none";
  }
}

document.getElementById("searchInput").addEventListener("keyup", filter);
Enter fullscreen mode Exit fullscreen mode

您的表格最终应该看起来与此类似:

响应式表格

总结

只需使用 HTML、CSS 和 JavaScript,您就可以创建一些具有高级功能的真正时尚的元素。

希望你能从中学到一些东西。再次强调,你可以在 CodePen 上查看代码,并根据自己的喜好进行调整。

感谢您的关注。

P/S:如果你喜欢这类内容丰富的帖子,可以考虑订阅我的时事通讯

文章来源:https://dev.to/ubahthebuilder/how-to-build-a-responsive-form-with-filter-functionity-using-html-css-and-javascript-3fka
PREV
用简单的英语学习 React
NEXT
20本免费电子书助您深入学习JavaScript