一个实用的表格(锁定表头,可调整单元格大小,可排序)
昨天在网上找到一个不错的表格显示,该表格可以锁定表头,可调整单元格的大小,同时还可以对数据进行排序,显示效果如下:
原代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0052)http://qbit.100steps.net/javascript/%B1%ED%B8%F1.htm -->
<HTML><HEAD><TITLE>表格</TITLE>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<STYLE>BODY {}{
BACKGROUND: #d4d0c8; SCROLLBAR-ARROW-COLOR: #002d96; SCROLLBAR-BASE-COLOR: #c2cbcf; scrollbar-3d-light-color: #ffffff
}
TABLE {}{
TABLE-LAYOUT: fixed; FONT-SIZE: 9pt; CURSOR: default
}
TR {}{
HEIGHT: 15px; ; BACKGROUND-COLOR: expression((this.sectionRowIndex%2)?"#ffffff":"#efefef")
}
TD {}{
PADDING-LEFT: 2px
}
#TList {}{
BORDER-RIGHT: #666 1px solid; MARGIN: 40px 10px 10px 70px; OVERFLOW: hidden; BORDER-LEFT: #666 1px solid; WIDTH: 600px; BORDER-BOTTOM: #666 1px solid; HEIGHT: 350px
}
#THead {}{
MARGIN-TOP: 0px; BACKGROUND: #efefef; MARGIN-LEFT: -1px; OVERFLOW: hidden; ; WIDTH: expression(this.parentNode.offsetWidth); HEIGHT: 22px
}
#TBody {}{
MARGIN-TOP: 0px; BACKGROUND: #ffffff; MARGIN-LEFT: -1px; OVERFLOW: scroll; ; WIDTH: expression(this.parentNode.offsetWidth); ; HEIGHT: expression(this.parentNode.offsetHeight-23)
}
#Ttitle {}{
BORDER-RIGHT: buttonshadow 1px solid; BORDER-TOP: buttonhighlight 1px solid; BACKGROUND: #d6d3ce; BORDER-LEFT: buttonhighlight 1px solid; ; WIDTH: expression(this.parentNode.offsetWidth); BORDER-BOTTOM: buttonshadow 1px solid; HEIGHT: 21px
}
</STYLE>
<SCRIPT language=javascript>
function Table() //创建容器
{
var MyTable = document.createElement("div");
document.getElementsByTagName("body")[0].appendChild(MyTable);
MyTable.setAttribute("id" , "TList");
var MyHead = document.createElement("div");
MyTable.appendChild(MyHead);
MyHead.setAttribute("id" , "THead");
var MyBody = document.createElement("div");
MyTable.appendChild(MyBody);
MyBody.setAttribute("id" , "TBody");
MyBody.onscroll = HeadScroll;
MyHead.innerHTML ="<table onselectstart=\"return false\" id=\"MyHeadTab\" border=1 cellpadding=\"0\" cellspacing=\"0\" bordercolordark=\"#FFFFFF\" bordercolorlight=\"#6C6969\"></table>";
MyBody.innerHTML ="<table id=\"MyBodyTab\" border=1 bordercolor=#cccccc style=\"border-collapse:collapse;\" frame=void></table>";
AddCell();
}
function AddCell() //增加列
{
var arg = 1;
if (arguments.length < 1) //增加空列
arg = 0;
for (var i = 0; i < arguments.length; i++) //参数不足
if (arguments[i].length < 1 && arg == 1)
return;
var H = document.getElementById("MyHeadTab");
if (H.rows.length < 1)
{
var Row = H.insertRow();
Row.setAttribute("id" , "Ttitle");
Row.onmousedown = ChangWidth;
Row.onmousemove = ChangCursor;
}
H = H.rows(0);
var B = document.getElementById("MyBodyTab");
var Tcell;
var CellIndex = H.cells.length - 1;
if (arguments[3] != undefined)
if (arguments[3] == -1)
{
if (H.cells[0].innerText != "序号")
return;
for (var i = 0; i < B.rows.length; i++)
B.rows[i].cells(0).innerText = i + 1;
return;
}
else
CellIndex = arguments[3];
if (CellIndex == -1)
Tcell = H.insertCell();
else
Tcell = H.insertCell(CellIndex);
if (arg == 0)
{
Tcell.innerText = " ";
Tcell.style.width = 1500;
}
else
{
Tcell.innerText = arguments[0];
Tcell.style.width = arguments[2];
}
Tcell.oType = arguments[1];
for (var i = 0; i < B.rows.length; i++)
{
var Bcell = B.rows(i).insertCell(CellIndex);
Bcell.style.width = arguments[2];
if (CellIndex == 0)
Bcell.innerHTML = i + 1;
}
}
function AddRow(Text) //增加行
{
if (Text == undefined)
return;
var B = document.getElementById("MyBodyTab");
var len = document.getElementById("MyHeadTab").rows(0).cells;
var Row = B.insertRow();
var Str = Text.split(",");
if (len[0].innerText == "序号")
Str.unshift(Row.sectionRowIndex + 1);
for (var i = 0; i < len.length; i++)
{
var Cell = Row.insertCell();
if (i + 1 != len.length)
{
Cell.innerHTML = Str[i] == undefined ? "" : Str[i];
Cell.style.width = document.getElementById("MyHeadTab").rows(0).cells[i].style.width;
}
}
Row.onmouseover = function() {
if (this.style.background == "#2a63de")
return;
this.style.background = "#3a6ea5";
this.style.color = "#ffffff";
}
Row.onmouseout = function() {
if (this.style.background == "#2a63de")
return;
this.style.background = (this.sectionRowIndex % 2) ? "#ffffff" : "#efefef";
this.style.color = "#000000";
}
Row.onclick = function() {
for (var i = 0; i < document.getElementById("MyBodyTab").rows.length; i++) //可以用折半查找以提高效率
{
/**//* //此行用于清除列选中
for (var j = 0; j < document.getElementById("MyBodyTab").rows(i).cells.length; j++)
if (document.getElementById("MyBodyTab").rows(i).cells[j].bgColor == "#2a63de")
document.getElementById("MyBodyTab").rows(i).cells[j].bgColor = "";
*/
with(document.getElementById("MyBodyTab").rows(i))
{
if (style.background == "#2a63de")
{
style.background = (i % 2) ? "#ffffff" : "#efefef";
style.color = "#000000";
break;
}
}
}
this.style.background = "#2a63de";
this.style.color = "#ffffff";
}
}
function HeadScroll()
{
document.getElementById("THead").scrollLeft = document.getElementById("TBody").scrollLeft;
}
function ChangWidth()
{
var e = event.srcElement;
if (e == undefined)
return;
if (e.tagName != "TD")
return;
var H = document.getElementById("MyHeadTab");
var B = document.getElementById("MyBodyTab");
var CellIndex;
for (var i = 0; i < H.rows(0).cells.length; i++)
if (H.rows(0).cells[i] == e)
{
CellIndex = i;
break;
}
var l = e.offsetLeft + 70;
if (e.style.cursor == "e-resize") //是改变列宽
{
e.setCapture();
document.onmousemove = function ()
{
if (e == undefined)
return;
e.style.cursor = "e-resize";
var w = event.x + document.getElementById("THead").scrollLeft - l;
if (w >= 5)
{
e.style.width = w;
if (B.rows.length < 1)
return;
B.rows(0).cells[CellIndex].style.width = w;
if(typeof(Y) != "undefined")
clearTimeout(Y);
if (B.rows.length < 50) //防止排序有Bug
Y = setTimeout("ChangWidthx("+ CellIndex +")" , 100);
else
Y = setTimeout("ChangWidthx("+ CellIndex +")" , 800);
}
HeadScroll();
}
document.onmouseup = function ()
{
if (e == undefined)
return;
e.releaseCapture();
e = undefined;
}
}
else
{
//排序
if (event.button == 1)
TdSort(CellIndex);
//SelectCell(CellIndex);
}
}
function ChangWidthx(CellIndex)
{
var B = document.getElementById("MyBodyTab");
var w = document.getElementById("MyHeadTab").rows(0).cells[CellIndex].style.width;
for (var i = 0; i < B.rows.length; i++)
B.rows(i).cells[CellIndex].style.width = w;
B.rows(0).cells[B.rows(0).cells.length-1].style.width = 0;
if (B.offsetWidth < B.parentNode.parentNode.offsetWidth)
B.rows(0).cells[B.rows(0).cells.length-1].style.width = B.parentNode.parentNode.offsetWidth - B.offsetWidth + 20;
HeadScroll();
}
function ChangCursor()
{
var e = event.srcElement;
if (e.tagName != "TD")
return;
var x = event.x + document.getElementById("THead").scrollLeft; //此值在固定表头时要更改
var l = e.offsetLeft + 70;
if (x >= l + e.offsetWidth + 8)
e.style.cursor = "e-resize";
else
e.style.cursor = "default";
}
function TdSort(CellIndex)
{
var Text = "↑";
var S = 1; //向上排
var H = document.getElementById("MyHeadTab");
var This = H.rows(0).cells[CellIndex];
if (This.innerText == "序号" || This.innerText == " ")
return; //没有数据或序号列,不排序
if (This.innerText.indexOf("↑") != -1)
{
Text = "↓";
S = 0;
}
for (var i = 0; i < H.rows(0).cells.length; i++)
{
var Ttitle = H.rows(0).cells[i];
if (Ttitle.innerText.indexOf("↑") != -1 || Ttitle.innerText.indexOf("↓") != -1)
{
Ttitle.innerText = Ttitle.innerText.substring(0 , Ttitle.innerText.length - 2);
break;
}
}
This.innerText += " "+ Text;
TSort(CellIndex , This.oType , S); //开始排序
}
function TSort(CellIndex , oType , Type)
{
var Temp = document.getElementById("MyBodyTab").tBodies[0].rows;
var A = new Array();
for (var i = 0; i < Temp.length; i++)
A[i] = Temp[i];
A.sort(SortSub(CellIndex , oType , Type));
for (var i = 0; i < A.length; i++)
document.getElementById("MyBodyTab").tBodies[0].appendChild(A[i]);
setTimeout("AddCell(\"序号\" , \"Num\" , 40 , -1)" , 1000);
}
function parseStr(s)
{
return String(s).toUpperCase();
}
function parseDate(s)
{
return Date.parse(s.replace(/\-/g, '/'));
}
function SortSub(CellIndex , oType , Type)
{
var ThisType = String;
if (oType == "Num")
ThisType = Number;
else if (oType == "Date")
ThisType = parseDate;
else if (oType == "Str")
ThisType = parseStr;
return function (x,y)
{
if (ThisType(x.cells[CellIndex].innerText) > ThisType(y.cells[CellIndex].innerText))
return Type ? 1 : -1;
if (ThisType(x.cells[CellIndex].innerText) < ThisType(y.cells[CellIndex].innerText))
return Type ? -1 : 1;
return 0;
};
}
function window.onload()
{
Table();
AddCell("姓名" , "Text" , 70);
AddCell("年龄" , "Num" , 55);
AddCell("性别" , "Str" , 55);
AddCell("地址" , "Text" , 120);
AddCell("联系电话" , "Text" , 120);
AddCell("E-mail" , "Text" , 120);
AddCell("序号" , "Num" , 40 , 0);
AddCell("身份证号码" , "Text" , 120);
for (var i = 0; i < 30; i++)
AddRow("小刚,"+ (24+i) +",男,传化物流基地,82878566,lzg1215@hotmail.com,41302619821215");
}
</SCRIPT>
<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
<BODY></BODY></HTML>
可惜所有代码都是用javascript写的,数据添加也是用javascript动态添加的。
我想把它应用在ASP.NET的程序中,通过一个repeater控件将数据库中的数据动态取出来,显示出如上效果。
经过我一个下午的调试修改,终于实现了我的想法。下面是源代码:
default.css:
BODY {}{
/**//*BACKGROUND: #d4d0c8;
SCROLLBAR-ARROW-COLOR: #002d96;
SCROLLBAR-BASE-COLOR: #c2cbcf;
scrollbar-3d-light-color: #ffffff*/
scrollbar-face-color: #ffffff;
scrollbar-shadow-color: #006699;
scrollbar-base-color : #ffffff;
scrollbar-highlight-color: #006699;
scrollbar-3dlight-color: #ffffff;
scrollbar-darkshadow-color: #ffffff;
scrollbar-track-color: #f8f8f8;
scrollbar-arrow-color: #006699;
}
/**//*TABLE {
TABLE-LAYOUT: fixed;
FONT-SIZE: 9pt;
CURSOR: default
}*/
.TR {}{
HEIGHT: 20px;
BACKGROUND-COLOR: expression((this.sectionRowIndex%2)?"#ffffff":"#efefef")
}
.TD {}{
PADDING-LEFT: 2px
}
#MyHeadTab
{}{
TABLE-LAYOUT: fixed; FONT-SIZE: 9pt; CURSOR: default
}
#MyBodyTab
{}{
TABLE-LAYOUT: fixed; FONT-SIZE: 9pt; CURSOR: default
}
#TList {}{
BORDER-RIGHT: #666 1px solid;
BORDER-LEFT: #666 1px solid;
BORDER-BOTTOM: #666 1px solid;
OVERFLOW: hidden;
MARGIN: 40px 10px 10px 70px;
/**//*
WIDTH: 600px;
HEIGHT: 350px;*/
}
#THead {}{
MARGIN-TOP: 0px;
BACKGROUND: #efefef;
MARGIN-LEFT: -1px;
OVERFLOW: hidden;
WIDTH: expression(this.parentNode.offsetWidth);
HEIGHT: 25px;
}
#TBody {}{
MARGIN-TOP: 0px;
BACKGROUND: #ffffff;
MARGIN-LEFT: -1px;
OVERFLOW: scroll;
WIDTH: expression(this.parentNode.offsetWidth);
HEIGHT: expression(this.parentNode.offsetHeight-25)
}
#Ttitle {}{
BORDER-RIGHT: buttonshadow 1px solid;
BORDER-TOP: buttonhighlight 1px solid;
BACKGROUND: #d6d3ce;
BORDER-LEFT: buttonhighlight 1px solid;
WIDTH: expression(this.parentNode.offsetWidth);
BORDER-BOTTOM: buttonshadow 1px solid;
HEIGHT: 24px
}
<%@ Page language="c#" Codebehind="Table.aspx.cs" AutoEventWireup="false" Inherits="JavaScriptDemo.Table" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>Table</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<META content="MSHTML 6.00.2900.2963" name="GENERATOR">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<link type="text/css" href="css/default.css" rel="stylesheet">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<div id="TList" style="WIDTH: 700px; HEIGHT: 450px">
<div id="THead">
<table onselectstart="return false" id="MyHeadTab" border="1" cellpadding="0" cellspacing="0"
bordercolordark="#ffffff" bordercolorlight="#6c6969">
<tr id="Ttitle" onmousedown="ChangWidth();" onmousemove="ChangCursor();">
<td width="35" align="center">序号</td>
<td width="100" align="center">客户编号</td>
<td width="200" align="center">公司名称</td>
<td width="100" align="center">客户名称</td>
<td width="100" align="center">地址</td>
<td width="60" align="center">城市</td>
<td width="100" align="center">电话</td>
<td width="100" align="center">传真</td>
<td width="23"></td>
</tr>
</table>
</div>
<div id="TBody" onscroll="HeadScroll();">
<asp:Repeater id="rptTB" runat="server" EnableViewState="False">
<ItemTemplate>
<tr class="tr" id='<%# String.Format("TR{0}",Container.ItemIndex+1)%>' onmouseover='rowover(<%# String.Format("TR{0}",Container.ItemIndex+1)%>);' onmouseout='rowout(<%# String.Format("TR{0}",Container.ItemIndex+1)%>);' onclick='rowclick(<%# String.Format("TR{0}",Container.ItemIndex+1)%>);'>
<td width="35" align="center" class="td"><%# Container.ItemIndex+1%></td>
<td width="100" align="center" class="td"><%# DataBinder.Eval(Container.DataItem,"CustomerID")%></td>
<td width="200" class="td"><%# DataBinder.Eval(Container.DataItem,"CompanyName")%></td>
<td width="100" class="td"><%# DataBinder.Eval(Container.DataItem,"ContactName")%></td>
<td width="100" class="td"><%# DataBinder.Eval(Container.DataItem,"Address")%></td>
<td width="60" align="center" class="td"><%# DataBinder.Eval(Container.DataItem,"City")%></td>
<td width="100" align="center" class="td"><%# DataBinder.Eval(Container.DataItem,"Phone")%></td>
<td width="100" align="center" class="td"><%# DataBinder.Eval(Container.DataItem,"Fax")%></td>
<td></td>
</tr>
</ItemTemplate>
<HeaderTemplate>
<table id="MyBodyTab" border="1" bordercolor="#cccccc" style="border-collapse:collapse;"
frame="void">
</HeaderTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater></div>
</div>
</form>
<script language="javascript">
function resetcolor()
{
var obj=document.getElementById("MyBodyTab");
for(var i = 0; i <obj.rows.length; i++)
{
obj.rows(i).style.background = (i%2)? "#ffffff" : "#efefef";
}
}
function rowover(obj) {
if (obj.style.background == "#2a63de")
return;
obj.style.background = "#3a6ea5";
obj.style.color = "#ffffff";
}
function rowout(obj) {
if (obj.style.background == "#2a63de")
return;
obj.style.background = (obj.sectionRowIndex % 2) ? "#ffffff" : "#efefef";
obj.style.color = "#000000";
}
function rowclick(obj) {
for (var i = 0; i < document.getElementById("MyBodyTab").rows.length; i++) //可以用折半查找以提高效率
{
with(document.getElementById("MyBodyTab").rows(i))
{
if (style.background == "#2a63de")
{
style.background = (i % 2) ? "#ffffff" : "#efefef";
style.color = "#000000";
break;
}
}
}
obj.style.background = "#2a63de";
obj.style.color = "#ffffff";
}
function HeadScroll()
{
document.getElementById("THead").scrollLeft = document.getElementById("TBody").scrollLeft;
}
function ChangWidth()
{
var e = event.srcElement;
if (e == undefined)
return;
if (e.tagName != "TD")
return;
var H = document.getElementById("MyHeadTab");
var B = document.getElementById("MyBodyTab");
var CellIndex;
for (var i = 0; i <H.rows(0).cells.length; i++)
if (H.rows(0).cells[i] == e)
{
CellIndex = i;
break;
}
var l = e.offsetLeft + 70;
if (e.style.cursor == "e-resize") //是改变列宽
{
e.setCapture();
document.onmousemove = function ()
{
if (e == undefined)
return;
e.style.cursor = "e-resize";
var w = event.x + document.getElementById("THead").scrollLeft - l;
if (w >= 5)
{
e.style.width = w;
if (B.rows.length < 1)
return;
B.rows(0).cells[CellIndex].style.width = w;
if(typeof(Y) != "undefined")
clearTimeout(Y);
if (B.rows.length < 50) //防止排序有Bug
Y = setTimeout("ChangWidthx("+ CellIndex +")" , 100);
else
Y = setTimeout("ChangWidthx("+ CellIndex +")" , 800);
}
HeadScroll();
}
document.onmouseup = function ()
{
if (e == undefined)
return;
e.releaseCapture();
e = undefined;
}
}
else
{
//排序
if (event.button == 1)
TdSort(CellIndex);
}
}
function ChangWidthx(CellIndex)
{
var B = document.getElementById("MyBodyTab");
var H = document.getElementById("MyHeadTab");
var w = document.getElementById("MyHeadTab").rows(0).cells[CellIndex].style.width;
for (var i = 0; i < B.rows.length; i++)
B.rows(i).cells[CellIndex].style.width = w;
B.rows(0).cells[B.rows(0).cells.length-1].style.width = 0;
if (B.offsetWidth < B.parentNode.parentNode.offsetWidth)
{
B.rows(0).cells[B.rows(0).cells.length-1].style.width = B.parentNode.parentNode.offsetWidth - B.offsetWidth + 20;
}
HeadScroll();
}
function ChangCursor()
{
var e = event.srcElement;
if (e.tagName != "TD")
return;
var x = event.x + document.getElementById("THead").scrollLeft; //此值在固定表头时要更改
var l = e.offsetLeft + 70;
if (x >= l + e.offsetWidth + 8)
e.style.cursor = "e-resize";
else
e.style.cursor = "default";
}
function TdSort(CellIndex)
{
var Text = "↑";
var S = 1; //向上排
var H = document.getElementById("MyHeadTab");
var This = H.rows(0).cells[CellIndex];
if (CellIndex==0 || This.innerText =="")
return; //没有数据或序号列,不排序
if (This.innerText.indexOf("↑") != -1)
{
Text = "↓";
S = 0;//向下排
}
for (var i = 0; i < H.rows(0).cells.length; i++)
{
var Ttitle = H.rows(0).cells[i];
if (Ttitle.innerText.indexOf("↑") != -1 || Ttitle.innerText.indexOf("↓") != -1)
{
Ttitle.innerText = Ttitle.innerText.substring(0 , Ttitle.innerText.length - 2);
break;
}
}
This.innerText += " "+ Text;
TSort(CellIndex , This.oType , S); //开始排序
}
function TSort(CellIndex , oType , Type)
{
var Temp = document.getElementById("MyBodyTab").tBodies[0].rows;
var A = new Array();
for (var i = 0; i < Temp.length; i++)
A[i] = Temp[i];
A.sort(SortSub(CellIndex , oType , Type));
for (var i = 0; i < A.length; i++)
document.getElementById("MyBodyTab").tBodies[0].appendChild(A[i]);
}
function parseStr(s)
{
return String(s).toUpperCase();
}
function parseDate(s)
{
return Date.parse(s.replace(/\-/g, '/'));
}
function SortSub(CellIndex , oType , Type)
{
var ThisType = String;
if (oType == "Num")
ThisType = Number;
else if (oType == "Date")
ThisType = parseDate;
else if (oType == "Str")
ThisType = parseStr;
return function (x,y)
{
if (ThisType(x.cells[CellIndex].innerText) > ThisType(y.cells[CellIndex].innerText))
return Type ? 1 : -1;
if (ThisType(x.cells[CellIndex].innerText) < ThisType(y.cells[CellIndex].innerText))
return Type ? -1 : 1;
return 0;
};
}
</script>
</body>
</HTML>
Table.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace JavaScriptDemo
{
/**//// <summary>
/// Table 的摘要说明。
/// </summary>
public class Table : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Repeater rptTB;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!Page.IsPostBack) {
Database db = DatabaseFactory.CreateDatabase();
string strSel="select * from Customers";
DataSet ds = db.ExecuteDataSet(CommandType.Text,strSel);
this.rptTB.DataSource =ds;
this.rptTB.DataBind();
}
}
Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}