TableWidget , 固定表头的一个js插件
时间:2010-10-14 来源:Yithcn
公司项目里面很多地方都需要用到,出列表的时候固定表头,滚动表体
思路就是动态创建一个div,然后里面创建2个div,一个title,一个body
然后用clone的方法,分别处理2个div的内容
使用说明: var tableWidget = new TableWidget("TableID", "DestID", "100%", "300px");
tableWidget.change();
表格需要固定宽度,table 需要加 style="table-layout: fixed;"
/*
* 函数名称: Widget
* 作 者: yithcn
* 功能说明: 固定表格头,表体可以滚动
* 创建日期: 2010.10.13
*/
function TableWidget(table, dest, width, height) {
this.construct(table, dest, width, height);
};
TableWidget.prototype = {
table: null,
dest: null,
widht: null,
tdiv: null,
bdiv: null,
create: function() {
var that = this;
var div = document.createElement("div");
div.style.cssText = "background-color:white;width:" + that.width;
that.dest.appendChild(div);
//title
var titlediv = document.createElement("div");
titlediv.style.cssText = "width:100%;";
div.appendChild(titlediv);
//body
var bodydiv = document.createElement("div");
bodydiv.style.cssText = "overflow:auto;";
bodydiv.appendChild(that.table);
div.appendChild(bodydiv);
var newtable = that.table.cloneNode(true);
var len = newtable.rows.length;
for (var i = len - 1; i > 0; i--) {
newtable.deleteRow(i);
}
titlediv.appendChild(newtable);
that.table.deleteRow(0);
that.tdiv = titlediv;
that.bdiv = bodydiv;
},
construct: function(table, dest, width, height) {
var that = this;
window.onload = function() {
if (table && typeof table == "string")
table = document.getElementById(table);
if (dest && typeof dest == "string")
dest = document.getElementById(dest);
else
dest = document.body;
width = width || "100%";
height = height || "300px";
height = parseInt(height) - table.rows[0].offsetHeight;
that.table = table;
that.dest = dest;
that.width = width;
that.height = height;
that.create();
that.change();
}
},
change: function() {
var that = this;
if (that.table.offsetHeight > parseInt(that.height)) {
that.tdiv.style.width = parseInt(that.bdiv.offsetWidth) - 16;
}
else {
that.tdiv.style.width = parseInt(that.bdiv.offsetWidth);
}
}
};
之所以会有一个change方法,是因为在项目当中需要动态改变列表,要计算表头和表体滚动条