只要在html页面上写一个table,引用下方的代码,就会自动完成上下左右多数据表头固定的功能.没有添加样式,大家可以随意自行添加。
jquery.fexedTabkeHead.js
(function ($) {
$.fn.extend({
FixedHead: function (options) {
var defualts={
rows:"1",
multiFlag:false,
thFlag:true,
}
var op = $.extend({ tableLayout: "auto" },defualts, options);
var tableCount = 1;
return this.each(function () {
var $this = $(this);
var _key = "_" + $this.attr("id");
if($("#divWrap"+_key).length == 0){
var $thisParentDiv = $(this).parent();
$thisParentDiv.wrap("<div id='divWrap"+_key+"' class='fixedtablewrap ' style='margin-top: 20px;'></div>").parent().css({ "position": "relative" }); //在当前table的父级DIV上,再加一个DIV
var x = $thisParentDiv.position();
/* x.left="1px";*/
var fixedDiv = $("<div id='divClone"+_key+"' class='fixedheadwrap fixhead ' style='clear:both;overflow:hidden;z-index:2;position:absolute;border-top: 1px solid #CCCCCC;' ></div>")
.insertBefore($thisParentDiv)
.css({ "width": $thisParentDiv[0].clientWidth, "left": x.left, "top": x.top });
var $thisClone = $this.clone(true);
$thisClone.attr("id","clone_table"+_key);
$thisClone.find("tbody").remove();
$thisClone.attr("style","margin:0 !important;");
$thisClone.appendTo(fixedDiv);
$this.css({ "marginTop": 0, "table-layout": op.tableLayout });
$thisParentDiv.scroll(function () { fixedDiv[0].scrollLeft = $(this)[0].scrollLeft; });
tableCount++;
}else{
var $thisClone = $("#clone_table"+_key);
}
$thisClone.find("th").each(function(idx,ele){ $(this).css("min-width",$this.find("th:eq("+idx+")").outerWidth()); $(this).css("max-width",$this.find("th:eq("+idx+")").outerWidth()); });
});
}
});
})(jQuery);