我正在使用bootstrap-table
并将dynamically
我的数据添加到表中(包括标题)
我检查了下面和其他相关帖子,但没有成功:
我尝试了 bootstrap-table 的 sticky-header 扩展,它在我滚动整个文档时可以工作,但是当我想将表格放在 div 容器内时,它不再起作用了。
我的 Codepen:示例
注意:我放置了数据作为示例,但实际上我使用 ajax 调用所有数据,然后初始化表格,这就是为什么我根本不在 html 中的表格内写任何东西,我需要它保持这种状态。
但在初始化之后,标题不再粘住。
我是 stackoverflow 的新手,所以我不确定我是否做对了,我无法将它变成小提琴,但这是我的代码,提前谢谢。
$(document).ready(function () {
var columns = [
{
field: "name",
title: "Name"
},
{
field: "age",
title: "Age"
},
{
field: "city",
title: "City"
}
];
var data = [
{ name: "John Doe", age: 28, city: "New York" },
{ name: "Jane Smith", age: 34, city: "Los Angeles" },
{ name: "Jane Smith", age: 34, city: "Los Angeles" },
{ name: "Jane Smith", age: 34, city: "Los Angeles" },
{ name: "Jane Smith", age: 34, city: "Los Angeles" },
{ name: "Mike Johnson", age: 45, city: "Chicago" },
{ name: "Sarah Lee", age: 30, city: "Miami" }
];
// init table
$("#RealTable").bootstrapTable({
data: data,
columns: columns
});
});
.divA {
width: 100%;
max-height: 200px; /* 設定 divA 高度為 50vh */
overflow: auto; /* 允許內部內容捲動 */
background-color: #e0e0e0;
padding: 20px;
position: relative; /* 需要這個來使 sticky 正常工作 */
}
/* 讓整個 table 設置 sticky */
#RealTable {
position: relative;
z-index: 1; /* 確保表格始終顯示 */
border-collapse: separate;
border-spacing:0;
text-align:center;
}
.sticky-header th {
position: sticky !important;
top: 0;
background-color: turquoise;
color: white;
z-index: 30 !important; /* 確保標題始終位於其他內容上方 */
}
.sticky-header th .th-inner {
position: sticky !important;
top: 0;
}
th,
td {
padding: 10px;
border: 1px solid #ddd;
text-align: center;
}
.content {
padding: 0px 0px 50px 0px;
}
.table {
width: 100%;
border: 1px solid #ddd;
text-align: center;
}
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sticky Header with Bootstrap Table</title>
<!-- 引入 Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<!-- 引入 bootstrap-table 的 CSS -->
<link href="https://unpkg.com/bootstrap-table/dist/bootstrap-table.min.css" rel="stylesheet">
</head>
<body>
<div class="section">
<h1>title</h1>
<p>qweqwewq</p>
</div>
<div class="divA">
<div class="row table-responsive">
<table id="RealTable" class="table table-hover text-nowrap">
<thead class="sticky-header">
</thead>
<tbody>
<!-- dynamic added -->
</tbody>
</table>
</div>
</div>
<div class="section">
<h1>title2</h1>
<p>qweqwewq</p>
<p>qweqwewq</p>
<p>qweqwewq</p>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<!-- bootstrap-table 的 JS -->
<script src="https://unpkg.com/bootstrap-table/dist/bootstrap-table.min.js"></script>
</body>
</html>
目前的工作(非粘性标题):
我想要的结果(表格内的粘性标题):