jquery.fixme是一款头部固定的响应式jQuery表格插件。该表格通过jQuery来构造固定的表格头效果,在页面向下滚动时,表格头固定在页面的顶部。
使用方法
HTML结构
该表格的HTML结构使用标准的HTML表格的结构:
< table class = "blue" > < thead > < tr > < th >列1</ th > < th >列2</ th > < th >列3</ th > </ tr > </ thead > < tbody > < tr > < td >单元格1</ td > < td >单元格2</ td > < td >单元格3</ td > </ tr > ...... </ tbody > </ table > |
CSS样式
该表格所需的样式非常简单,它提供了2中颜色主题:蓝色和紫色。
.container{ width : 90% ; margin : auto ; } table{ border-collapse : collapse ; width : 100% ; } . blue { border : 2px solid #1ABC9C ; } . blue thead{ background : #1ABC9C ; } . purple { border : 2px solid #9B59B6 ; } . purple thead{ background : #9B59B6 ; } |
通过nth-child
为表格偶数行设置斑马线效果。
tbody tr:nth-child(even){ background : #ECF0F1 ; } |
鼠标滑过表格时修改表格行的背景色和文字颜色。
tbody tr:hover{ background : #BDC3C7 ; color : #FFFFFF ; } |
.fixed
类用于固定表格头,定位方式使用固定定位,开始是是不可见的。
. fixed { top : 0 ; position : fixed ; width : auto ; display : none ; border : none ; } |
JavaScript
在Js代码中,通过$.fn.fixMe
构造了一个简单的表格头部固定插件。该插件中有3个方法:初始化方法init()
,头部尺寸修改方法resizeFixed()
和头部滚动固定方法scrollFixed()
。然后以参数的形式将后两个方法分别传入window
对象的resize()
和scroll()
方法中。
;( function ($) { $.fn.fixMe = function () { return this .each( function () { var $ this = $( this ), $t_fixed; function init() { $ this .wrap( '<div class="container" />' ); $t_fixed = $ this .clone(); $t_fixed.find( "tbody" ).remove().end().addClass( "fixed" ).insertBefore($ this ); resizeFixed(); } function resizeFixed() { $t_fixed.find( "th" ).each( function (index) { $( this ).css( "width" ,$ this .find( "th" ).eq(index).outerWidth()+ "px" ); }); } function scrollFixed() { var offset = $( this ).scrollTop(), tableOffsetTop = $ this .offset().top, tableOffsetBottom = tableOffsetTop + $ this .height() - $ this .find( "thead" ).height(); if (offset < tableOffsetTop || offset > tableOffsetBottom) $t_fixed.hide(); else if (offset >= tableOffsetTop && offset <= tableOffsetBottom && $t_fixed.is( ":hidden" )) $t_fixed.show(); } $(window).resize(resizeFixed); $(window).scroll(scrollFixed); init(); }); }; })(jQuery); |
最后在页面DOM元素加载完毕之后,通过fixMe()
方法来初始化插件。
$(document).ready( function (){ $( "table" ).fixMe(); }); |
jquery.fixme固定表格头插件的github地址为:https://github.com/ispot-tv/jquery.fixme