我有一个包含垂直和水平方向数据的巨大表格......
像这样:jsfiddle
我希望将最左边的列和顶行固定,以便在我向两个方向滚动时,我能够将这两个(列和行)保持在原位。但只是移动内容。
如何使用JS / CSS实现这一目标?
我猜一个纯粹的CSS解决方案不会这样做,因为有一个双向滚动。
someclass { position: fixed }
答案 0 :(得分:2)
回答您的问题所需的完整代码太大,无法包含在此处。相反,我会将您链接到保留答案的JSBin,并且只包含样式和javascript。
警告是:
position: fixed
样式属性时,您基本上将它们从表中分离出来。
div
,你可以position: fixed
并模拟列标题的当前行为强> HTML:
<!-- Notice I removed background and border color from table tag -->
<table border="0" width="100%" cellpadding="3" cellspacing="1">
<tr>
<td>Dead Cell</td><!-- this cell is not shown -->
...
CSS:
/* Make white space above table since we broke the column headers out of the table */
table {
margin-top: 51px;
position: relative;
}
table td {
border: 1px solid #FFCC00;
height: 44px;
background-color: #FFFFCC;
}
/* styling for column headers */
table tr:first-child {
position: fixed;
top: 0;
left: 57px;
z-index: 100;
}
/* remove first cell in top left position */
table tr:first-child td:first-child {
display: none;
}
table tr:first-child td,
table tr {
position: relative;
}
table tr:first-child td {
background: orange;
}
table tr td:first-child {
background: orange;
position: fixed;
width: 39px
}
/* Make white space to the left of table since we broke the row headers out of the table */
table tr:nth-child(n+2) td:nth-child(2) {
margin-left: 48px;
display: block;
}
JS:
$(function(){ // When document is loaded and ready
$(window).scroll(function() { // When we scroll in the window
// Move column headers into place
$('table tr:first-child td').css('left', - $(this).scrollLeft());
// Move row headers into place
$('table tr td:first-child').each(function() {
$(this).position({ // jQuery UI overloaded function
my: "left top",
at: "left top",
of: $(this).parent(),
using: function(pos) {
$(this).css('top', pos.top);
}
});
});
});
});
同样,这里是指向JSBin的链接。