修复了具有固定横幅div的表头

我已经使用来自这个SO问题的代码来成功创建固定的表头,但是我有一些问题使它适应我的页面,我无法弄清楚。 我对Javascript / jQuery有点新意,所以请耐心等待一下。

代码依赖浏览器中的scroll事件来检测THEAD何时不在视图中,以便它知道何时克隆表并将克隆的标题放在页面顶部。
但是我的页面有一个DIV固定在页面顶部,其中包含一个搜索栏等,当这个存在时,固定标题不起作用。 因为我需要固定区域,所以我很难找到解决方法。 它可能很简单,但我没有看到它。

代码段如下:

function moveScroll() { var scroll = $(window).scrollTop(); var anchor_top = $("#maintable").offset().top; var anchor_bottom = $("#bottom_anchor").offset().top; if (scroll > anchor_top && scroll < anchor_bottom) { clone_table = $("#clone"); if (clone_table.length === 0) { clone_table = $("#maintable").clone(); clone_table.attr({ id: "clone" }).css({ position: "fixed", "pointer-events": "none", top: 0 }).width($("#maintable").width()); $("#table-container").append(clone_table); $("#clone").width($("#maintable").width()); $("#clone").css({ border: "none" }); $("#clone thead").css({ visibility: "true" }); $("#clone tbody").css({ visibility: "hidden" }); var footEl = $("#clone tfoot"); if (footEl.length) { footEl.css({ visibility: "hidden" }); } } } else { $("#clone").remove(); } } $(window).scroll(moveScroll); 

这是一个带有页面精简版的JSFiddle。

http://jsfiddle.net/urvfE/

如果删除#topsection#table-container的CSS部分,您将看到正在运行的固定标题。 当这些部分存在时,没有任何作用。

另外,我还有另外一个问题。 如果我使用border-collapse:collapse在桌面上border-collapse:collapse以获得漂亮的边框Firefox不会正确渲染固定的标头。 它会在顶部呈现一个完整的空表。 任何想法如何绕过这个?

我在周末之后回到了这个问题并解决了它。 我不敢相信上周我看不到这个! 它certificate了一双新鲜的眼睛能做什么。
我想我会在这里回答,以防其他人想要这个代码。

我更改了其中一个变量来监听主要部分的顶部而不是整个窗口:

 var scroll = $(window).scrollTop(); 

就是现在:

 var scroll = $('#table-container').offset().top; 

然后我更改了语句来调用函数:

 $(window).scroll(moveScroll); 

就是现在:

 $('#table-container').scroll(moveScroll); 

最后,我手动将固定标题的顶部设置为130px以匹配顶部的底部。

这是一个小提琴: http : //jsfiddle.net/hvRZy/

我仍然无法解决边界崩溃的问题 ,如果有人在这方面有任何想法,那将是惊人的。 谢谢!

编辑:我已设法用以下CSS解决了边框问题(还添加了圆角):

 table { border-collapse: separate; border-spacing: 0px; } table tr th, table tr td { border-right: 1px solid #000; border-bottom: 1px solid #000; padding: 5px; } table tr th:first-child, table tr td:first-child { border-left: 1px solid #000; } table tr th { background: #c0c0c0; border-top: 1px solid #000; text-align: center; } table tr:first-child th:first-child { border-top-left-radius: 6px; } table tr:first-child th:last-child { border-top-right-radius: 6px; } table tfoot tr:last-child td:first-child { border-bottom-left-radius: 6px; } table tfoot tr:last-child td:last-child { border-bottom-right-radius: 6px; } 

最后一个小提琴! http://jsfiddle.net/KfxQg/

你可以使用jQuery TH Float插件 。 如果你想让table th得到修复,你可以像这样使用它

 $("#maintable").thfloat({ attachment : "#maintable", noprint : false }); 

小提琴