我想在水平和垂直方向上添加滚动到我的html表格。但是只允许tbody滚动,并且应该在垂直滚动tbody时固定,并在水平滚动tbody时滚动/调整。我知道我必须将溢出的css属性应用于tbody然后在它之后,使用jquery调整带宽度的宽度。如果有人知道解决方案,那么答案将不胜感激。这是我的代码。
HTML部分
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
<td>Row 2</td>
<td>Row 2</td>
<td>Row 2</td>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
<td>Row 3</td>
<td>Row 3</td>
<td>Row 3</td>
<td>Row 3</td>
</tr>
<tr>
<td>Row 4</td>
<td>Row 4</td>
<td>Row 4</td>
<td>Row 4</td>
<td>Row 4</td>
</tr>
<tr>
<td>Row 5</td>
<td>Row 5</td>
<td>Row 5</td>
<td>Row 5</td>
<td>Row 5</td>
</tr>
<tr>
<td>Row 6</td>
<td>Row 6</td>
<td>Row 6</td>
<td>Row 6</td>
<td>Row 6</td>
</tr>
<tr>
<td>Row 7</td>
<td>Row 7</td>
<td>Row 7</td>
<td>Row 7</td>
<td>Row 7</td>
</tr>
<tr>
<td>Row 8</td>
<td>Row 8</td>
<td>Row 8</td>
<td>Row 8</td>
<td>Row 8</td>
</tr>
<tr>
<td>Row 9</td>
<td>Row 9</td>
<td>Row 9</td>
<td>Row 9</td>
<td>Row 9</td>
</tr>
<tr>
<td>Row 10</td>
<td>Row 10</td>
<td>Row 10</td>
<td>Row 10</td>
<td>Row 10</td>
</tr>
</tbody>
</table>
CSS
html {
font-family: verdana;
font-size: 10pt;
line-height: 25px;
}
table {
border-collapse: collapse;
width: 300px;
overflow-x: scroll;
display: block;
}
thead {
background-color: #EFEFEF;
}
thead, tbody {
display: block;
}
tbody {
overflow-y: scroll;
overflow-x: hidden;
height: 140px;
}
td, th {
min-width: 100px;
height: 25px;
border: dashed 1px lightblue;
}
JS
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<script type="text/javascript">
$('table').on('scroll', function () {
$("table > *").width($("table").width() + $("table").scrollLeft());
});
</script>
答案 0 :(得分:1)
http://codepen.io/EasonWang01/pen/bEjRvj尝试一下。
html {
font-family: verdana;
font-size: 10pt;
line-height: 25px;
}
table {
border-collapse: collapse;
width: 540px;
display: block;
}
thead {
background-color: #EFEFEF;
}
thead, tbody {
display: block;
}
tbody {
overflow-y: scroll;
height: 140px;
}
td, th {
min-width: 100px;
height: 25px;
border: dashed 1px lightblue;
}
答案 1 :(得分:0)
完成。因为我错误地启动了jquery功能。通过将js代码放入$(function () {});
,它就会被解决。