我不得不用容器 div 包装可滚动的 div 并稍微使用 if 语句,但它可以工作。
工作示例
JS
function stickyTitles(stickies) {
this.load = function () {
stickies.each(function () {
var thisSticky = jQuery(this).wrap('<div class="followWrap" />');
thisSticky.parent().height(thisSticky.outerHeight());
jQuery.data(thisSticky[0], 'pos', thisSticky.offset().top);
});
};
this.scroll = function () {
stickies.each(function (i) {
var thisSticky = jQuery(this),
nextSticky = stickies.eq(i + 1),
prevSticky = stickies.eq(i - 1),
pos = jQuery.data(thisSticky[0], 'pos'),
h = $('.mytable').offset().top;
if (pos <= jQuery('.mytable').scrollTop() + h) {
thisSticky.addClass("fixed");
if (nextSticky.length > 0 && jQuery('.mytable').scrollTop() + h >= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
thisSticky.addClass("absolute").css("top", jQuery.data(nextSticky[0], 'pos') - $('.mytable').scrollTop() - prevSticky.outerHeight() - h);
}
} else {
thisSticky.removeClass("fixed");
if (prevSticky.length > 0 && jQuery('.mytable').scrollTop() + h <= jQuery.data(thisSticky[0], 'pos') - prevSticky.outerHeight()) {
prevSticky.removeClass("absolute").removeAttr("style");
}
}
});
};
}
jQuery(document).ready(function () {
var newStickies = new stickyTitles(jQuery(".followMeBar"));
newStickies.load();
jQuery('.mytable').on("scroll", function () {
newStickies.scroll();
});
});
CSS
body {
height:2000px;
margin: 0;
background: #333;
color: #fff;
overflow: auto;
}
table {
width: 100%;
}
table tr {
height: 100px;
}
.followMeBar {
display: block;
background: #222;
border-bottom: solid 1px #111;
border-top: solid 1px #444;
position: relative;
z-index: 1;
width: 200%;
}
.followMeBar.fixed {
position: absolute;
top: 0;
width: 90%;
z-index: 0;
}
.followMeBar.fixed.absolute {
position: absolute;
}
.mytable {
overflow-y: scroll;
height: 250px;
}
#hidden {
overflow:hidden;
position:absolute;
width:100%;
}
HTML
<h1>Test</h1>
<p>My table in a div below...</p>
<div id="hidden">
<div class='mytable'>
<table>
<tr class='followMeBar'>
<td colspan="4">12-07-2013</td>
</tr>
<tr>
<td>4:35 PM</td>
<td>1729</td>
<td>2</td>
<td>jack</td>
</tr>
<tr>
<td>4:40 PM</td>
<td>KSKS</td>
<td>4</td>
<td>jason</td>
</tr>
<tr>
<td>5:35 PM</td>
<td>1714</td>
<td>4</td>
<td>raymond</td>
</tr>
etc...
</table>
</div>
</div>
请注意,此方法基于此答案,我不得不稍作调整以使其适用于可滚动的 div,但我想在应得的情况下给予信用。