在页面滚动上修复thead

情况:包含多行表的页面。 当滚动时,使用jquery或任何给定的脚本,当我们到达页面顶部时,我想修复thead。 我不想溢出桌子本身。

您可以稍微修改Lobstrosity的代码: position: fixed而不是absolute

position: fixed现在被IE8及其后的所有浏览器广泛采用。 BTW固定在移动/平板设备上比position: absolute更好。

我发现在每个列的动态宽度的表上,绝对定位的

会丢失其余列的宽度,所以为了解决这个问题,我想出了以下代码:

这段代码的作用如下:

通过查找第一个

行的CSS宽度并将其存储在数组中以供日后使用,确定表中每列的宽度。 当用户滚动类时,’fixed’被添加到

(默认浏览器行为将改变

的宽度,并且它们将与

不匹配。所以为了解决这个问题我们追溯将

的宽度设置为我们之前读过的值。

无论如何这里是代码:

CSS

 table.entries {width: 100%;border-spacing: 0px;margin:0;} table.entries thead.fixed {position:fixed;top:0;} 

HTML

 
Name Email Location DOB Opt in Added
Ricky Bobby ricky.bobby@email.com Kent, GB 20/08/1984 Yes 4 hours ago

JavaScript的

 TableThing = function(params) { settings = { table: $('#entriestable'), thead: [] }; this.fixThead = function() { // empty our array to begin with settings.thead = []; // loop over the first row of td's in <tbody> and get the widths of individual <td>'s $('tbody tr:eq(1) td', settings.table).each( function(i,v){ settings.thead.push($(v).width()); }); // now loop over our array setting the widths we've got to the <th>'s for(i=0;i $(window).scroll(function() { var windowTop = $(window).scrollTop(); if (windowTop > settings.table.offset().top) { $("thead", settings.table).addClass("fixed"); } else { $("thead", settings.table).removeClass("fixed"); } }); } } $(function(){ var table = new TableThing(); table.fixThead(); $(window).resize(function(){ table.fixThead(); }); }); 

这些function可以在FF 3.5,Chrome 3和IE 8中快速测试,您可以根据自己的需要进行定制。

它使用thead绝对定位。 当thead绝对定位时,这基本上将其从table的原始流动中移除,并且所有tbody的宽度相应地调整。 因此,如果您未指定列宽或任何列的标题比该列中的任何其他单元格宽,则会出现丑陋的行为。

CSS

 #Grid thead.Fixed { position: absolute; } 

HTML

 
A B C
1 2 3

jQuery的

 $(function() { var table = $("#Grid"); $(window).scroll(function() { var windowTop = $(window).scrollTop(); if (windowTop > table.offset().top) { $("thead", table).addClass("Fixed").css("top", windowTop); } else { $("thead", table).removeClass("Fixed"); } }); }); 

我注意到它在IE中不起作用,除非您指定严格的XHTML doctype:

    
 (function ($) { $.fn.fixedHeader = function () { return this.filter('table').each(function () { var that = this; var $head = $('
').addClass('head'); $(this).before($head); $('th', this).each(function () { var $el = $(this); var $div = $('
').width($el.outerWidth()).text( $el.text()); $head.append($div); }); $(window).on('scroll', function () { var $that = $(that); var w = $(window).scrollTop(); var o = $('th', that).first().offset().top; var tableO = $that.offset().top + $that.height(); if (o < w && tableO > w) { $head.show(); } else { $head.hide(); } }); }); }; })(jQuery);

你可以使用这个jquery插件(你需要使.head风格适应你的风格)。 这里的工作示例: http : //jsfiddle.net/lukasi/7K52p/1/