$.fn.extend({ tableHeaderFix:function (option) { var params = { h:0, }; //更改默认值 if(option && typeof(option) == 'object'){ $.each(option,function (i,v) { params[i] = v; }); } //所有单元格宽度设定 var cells = $(this).find('th,td'); $.each(cells,function (i,v) { var w = $(v).width(); $(v).css({'width':w+'px'}); }); //获取thead的jquery对象 var thead = $(this).find('thead'); var pos = thead.position(); var thead_w = thead.width(); //console.log(pos,thead_w); //滚动事件 var thead = $(this).find('thead'); var thead_w = thead.width(); $(document).scroll(function () { var scroH = $(document).scrollTop(); //滚动高度 if(scroH > (pos.top - params.h)){ thead.css({'position':'fixed','top':params.h+'px','width':thead_w+'px','z-index':1}); }else{ thead.css({'position':'relative'}); } }); } });
调用:$('table').tableHeaderFix({h:0});