正如标题所说,我正在使用django-tables2在Django中制作表格。我想要它,以便当我向下滚动页面并且表格的标题即将离开页面时,我希望它粘在页面的顶部,直到窗口再次向上滚动。不,我不想在页面中有一个可滚动的div。以下是一些相关文字:
tables.py
class Example(tables.Table):
field1 = tables.Column()
field2 = tables.Column()
field3 = tables.Column()
class Meta:
attrs = {'class': 'table table-striped', 'style': 'display: block; overflow: auto;'}
example.html的
<style></style>
<table>
<thead>
<tr>
<td>Field1</td>
<td>Field2</td>
<td>Field3</td>
</tr>
</thead>
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
</table>
<script></script>
使用CSS和JavaScript,有没有人有任何解决方案?我已经尝试了几种解决方案,但所有这些解决方案都没有对标题做任何事情。我正在使用jquery-3.2.1。感谢。
答案 0 :(得分:0)
尝试这样的事情:
window.onscroll = function() {
myFunction()
};
var navbar = document.getElementsByTagName("table")[0];
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
&#13;
.sticky {
position: fixed;
top: 0;
width: 180px;
margin: auto;
background: white;
}
.sticky+tbody {
padding-top: 60px;
}
table {
table-layout: auto;
width: 180px;
margin-top: 20px;
}
table,
th,
td {
border: 1px solid black;
}
table.one {
margin-bottom: -20px;
}
&#13;
<table class="one">
<thead>
<tr>
<td>Field1</td>
<td>Field2</td>
<td>Field3</td>
</tr>
</thead>
<tbody> </tbody>
</table>
<table class="two">
<tbody>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>Text</td>
</tr>
</tbody>
</table>
&#13;