请看一下 FIDDLE 。我在向下滚动页面时尝试让表格标题保持在最顶层。它没有像我预期的那样工作,因为当标题变得粘滞时,它会改变CSS样式,使它们脱离各自的列。我已经尝试将填充添加回#sticky.stick > th
,但没有任何改变。有什么建议吗?
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function () {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
HTML:
<div id="sticky-anchor"></div>
<table id="comparetable" class="blueshine">
<tr id="sticky">
<td class="blank"> </td>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
<tr>
<td class="rowTitle">Price</td> <td>$4.5</td>
<td>$3.5</td>
<td>$2.5</td>
<td>$1.5</td>
</tr>
<tr>
<td class="rowTitle">Discount</td> <td>50</td>
<td>60</td>
<td>40</td>
<td>30</td>
</tr>
<tr>
<td class="rowTitle">Location</td>
<td>Asia</td>
<td>Africa</td>
<td>Europe</td>
<td>Africa</td>
</tr>
<tr>
<td class="rowTitle">Location</td>
<td>Asia</td>
<td>Africa</td>
<td>Europe</td>
<td>Africa</td>
</tr>
</tbody>
</table>
CSS:
/* START COMPARISON TABLE STYLES */
#comparetable {width: 100%; table-layout: fixed; text-align: center; margin: 4em 0; border-collapse: collapse; }
#comparetable tr {background: transparent!important;}
#comparetable td,
#comparetable th {padding: 20px; text-align: center;}
#comparetable td.rowTitle {text-align: left;}
.blank {background: none!important; border: none!important;}
.blueshine th {background-color: #b8cee2; font-size: 22px; color: #0c3053; text-align: center; font-weight: 600; text-shadow: 0 1px 0 #e0ecf7; border: 1px solid #9fb6c8;}
.blueshine td {background-color: #f0f1f1; border: 1px solid #c8d6e2;}
.blueshine td.rowTitle {border-left: 4px solid #333}
/* END COMPARISON TABLE STYLES */
#sticky {
color: #222;
font-size: 2em;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
}
#sticky.stick > th {
padding: 20px;
}
答案 0 :(得分:1)
在CSS中进行更改:
.sticky {
color: #222;
font-size: 2em;
display:none;
}
.sticky.stick {
position:fixed;
display:inline;
top: 0;
z-index: 100;
}
.sticky #comparetable { margin:0; }
这是HTML,基本上你必须在#pix-anchor之后创建一个只有标题的新表,然后把你的表放在这个之后。
<div id="sticky-anchor"></div>
<div class="sticky">
<table id="comparetable" class="blueshine">
<tr>
<td class="blank"> </td>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</table>
</div>
<!-- your table goes here -->
<table id="comparetable" class="blueshine">
<tr> <!-- note that the id sticky has been removed -->
<td class="blank"> </td>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
<tr>...
将javascript更改为使用class而不是id:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('.sticky').addClass('stick');
} else {
$('.sticky').removeClass('stick');
}
}
希望这会有所帮助:)