如何用HTML实现表格可折叠?适配Thymeleaf场景
最简可折叠表格实现方案(适配Thymeleaf)
直接用HTML原生的<details>和<summary>标签就能实现需求,无需额外JS或复杂CSS,代码量极小,完美适配Spring Boot的Thymeleaf模板。
核心逻辑
<summary>作为可点击的标题,点击触发展开/折叠动作- 将表格嵌套在
<details>内部,作为折叠内容容器
Thymeleaf示例代码
<!-- 单个可折叠表格 --> <details> <summary>订单统计报表</summary> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>订单ID</th> <th>金额</th> <th>状态</th> </tr> </thead> <tbody> <!-- Thymeleaf循环渲染数据 --> <tr th:each="order : ${orderList}"> <td th:text="${order.id}"></td> <td th:text="${order.amount}"></td> <td th:text="${order.status}"></td> </tr> </tbody> </table> </details> <!-- 批量渲染可折叠表格(遍历多组标题+数据) --> <div th:each="dataGroup : ${dataGroups}"> <details> <summary th:text="${dataGroup.title}"></summary> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th th:each="header : ${dataGroup.headers}" th:text="${header}"></th> </tr> </thead> <tbody> <tr th:each="row : ${dataGroup.rows}"> <td th:each="cell : ${row}" th:text="${cell}"></td> </tr> </tbody> </table> </details> </div>
可选自定义样式
如果需要优化默认外观,只需添加少量CSS:
summary { cursor: pointer; font-weight: bold; padding: 8px; background-color: #f5f5f5; border: 1px solid #ddd; } details[open] summary { background-color: #e8f4f8; } table { margin-top: 8px; width: 100%; }
该方案完全基于原生HTML,无需依赖外部资源,代码量远少于传统JS实现,同时能无缝对接Thymeleaf的模板渲染逻辑。
内容的提问来源于stack exchange,提问作者nicku
相关产品推荐
相关产品推荐

