分享ASP.NET固定GridView表头的方法

分享ASP.NET固定GridView表头的方法

分享ASP.NET固定GridView表头的方法

——独立观察员 2015.03.27

最近接到一个任务,是需要将ASP.NET页面中的GridView的表头固定住,不随滚动条滚动,只是表身滚动。其实要实现得很完美,对我来说还是很难的,因为我对JS不熟练,虽然也自学过很多次,但总感觉一直入不了门,就像Android一样。还是C#给人一种平易近人的感觉,很好上手。

老大倒是给我指了条思路,说可以自己用html写表头,然后将GridView自身的表头隐藏就好了。我觉得这个听上去容易,真正做起来应该不简单吧。完全搞不定啊,还是问问度娘吧。

 

网上看到有人推荐这个

%title插图%num

用了一下,确实可以,也没有”ScrollableGridPlugin.js方法“的表头与表身错位的问题。

但问题还是有的,就是表格中文字都未换行,后来找到了原因:

%title插图%num(原先是 “nowarp”)

 

附——”white-space”介绍

white-space属性设置如何处理元素内的空白。所有浏览器都支持 white-space 属性。

可能的值

描述

normal

默认。空白会被浏览器忽略。

pre

空白会被浏览器保留。其行为方式类似 HTML 中的 <pre> 标签。

nowrap

文本不会换行,文本会在在同一行上继续,直到遇到 <br> 标签为止。

pre-wrap

保留空白符序列,但是正常地进行换行。

pre-line

合并空白符序列,但是保留换行符。

inherit

规定应该从父元素继承 white-space 属性的值。

(值 pre-wrap 和 pre-line 是 CSS 2.1 中新增的。)

 

言归正传,还有的问题就是浏览器窗口缩小后右边比较难看,且底部滑动条形同虚设,滑动后并不能展现到右边的表格内容:

%title插图%num

(尝试解决但未成功,请大家不吝赐教)

 

接下来先说说任务方面的处理:

由于菜单以下是iframe页面:

%title插图%num

 

所以可通过设置这个iframe引用的页面的高度,使得iframe页向上滚动到顶时刚好到合适的位置:

%title插图%num

 

这里主要就是设置这个表格的高度,这就要牵涉到本次固定表头方法的用法了。

 

之前提到的网页可下载2个JS文件和1个CSS文件(我用了Chrome插件”Quick Source Viewer”方便下载)。其中superTables.js 存放主要方法,jquery.superTable.js 存放快捷调用方法,superTables.css 则是样式了,三者都遵循MIT授权,是很宽松的一种Lisence。

 

调用方法(完整用法可看源代码):

%title插图%num

使用Jquery选取GridView,用width和height设置宽和高,fixedCols参数设置前几列固定,colWidths可指定各列的宽度,还有其它一些参数,比如有个可设置几行作为表头的(即固定前几行)。

 

有些人可能喜欢先在线看看代码再决定使不使用,我就满足他们吧:

1、jquery.superTable.js

/////////////////////////////////////////////////////////////////////////////////////////
// Super Tables Plugin for jQuery - MIT Style License
// Copyright (c) 2009 Jeffrey Lee --- blog.darkthread.net
//
// A wrapper for Matt Murphy's Super Tables http://www.matts411.com/post/super_tables/
//
// Contributors:
//
/////////////////////////////////////////////////////////////////////////////////////////
////// TO CALL: 
// $("...").toSuperTable(options)
//
////// OPTIONS: (order does not matter )
// cssSkin : string ( eg. "sDefault", "sSky", "sOrange", "sDark" )
// headerRows : integer ( default is 1 )
// fixedCols : integer ( default is 0 )
// colWidths : integer array ( use -1 for auto sizing )
// onStart : function ( any this.variableNameHere variables you create here can be used later ( eg. onFinish function ) )
// onFinish : function ( all this.variableNameHere variables created in this script can be used in this function )
// margin, padding, width, height, overflow...: Styles for "fakeContainer"
//
////// Example:
// $("#GridView1").toSuperTable(
//              { width: "640px", height: "480px", fixedCols: 2,
//                onFinish: function() { alert('Done!'); } })

(function($) {
    $.fn.extend(
            {
                toSuperTable: function(options) {
                    var setting = $.extend(
                    {
                        width: "640px", height: "320px",
                        margin: "10px", padding: "0px",
                        overflow: "hidden", colWidths: undefined,
                        fixedCols: 0, headerRows: 1,
                        onStart: function() { },
                        onFinish: function() { },
                        cssSkin: "sSky"
                    }, options);
                    return this.each(function() {
                        var q = $(this);
                        var id = q.attr("id");
                        q.removeAttr("style").wrap("<div id='" + id + "_box'></div>");

                        var nonCssProps = ["fixedCols", "headerRows", "onStart", "onFinish", "cssSkin", "colWidths"];
                        var container = $("#" + id + "_box");

                        for (var p in setting) {
                            if ($.inArray(p, nonCssProps) == -1) {
                                container.css(p, setting[p]);
                                delete setting[p];
                            }
                        }
                        
                        var mySt = new superTable(id, setting);

                    });
                }
            });
})(jQuery);

 

2、superTables.js

/////////////////////////////////////////////////////////////////////////////////////////
// Super Tables v0.30 - MIT Style License
// Copyright (c) 2008 Matt Murphy --- www.matts411.com
//
// Contributors:
// Joe Gallo
/////////////////////////////////////////////////////////////////////////////////////////
////// TO CALL: 
// new superTable([string] tableId, [object] options);
//
////// OPTIONS: (order does not matter )
// cssSkin : string ( eg. "sDefault", "sSky", "sOrange", "sDark" )
// headerRows : integer ( default is 1 )
// fixedCols : integer ( default is 0 )
// colWidths : integer array ( use -1 for auto sizing )
// onStart : function ( any this.variableNameHere variables you create here can be used later ( eg. onFinish function ) )
// onFinish : function ( all this.variableNameHere variables created in this script can be used in this function )
//
////// EXAMPLES:
// var myST = new superTable("myTableId");
//
// var myST = new superTable("myTableId", {
//		cssSkin : "sDefault",
//		headerRows : 1,
//		fixedCols : 2,
//		colWidths : [100, 230, 220, -1, 120, -1, -1, 120],
//		onStart : function () {
//			this.start = new Date();
//		},
//		onFinish : function () {
//			alert("Finished... " + ((new Date()) - this.start) + "ms.");
//		}
// });
//
////// ISSUES / NOTES:
// 1. No quirksmode support (officially, but still should work)
// 2. Element id's may be duplicated when fixedCols > 0, causing getElementById() issues
// 3. Safari will render the header row incorrectly if the fixed header row count is 1 and there is a colspan > 1 in one 
//		or more of the cells (fix available)
/////////////////////////////////////////////////////////////////////////////////////////

var superTable = function (tableId, options) {
/////* Initialize */
	options = options || {};
	this.cssSkin = options.cssSkin || "";
	this.headerRows = parseInt(options.headerRows || "1");
	this.fixedCols = parseInt(options.fixedCols || "0");
	this.colWidths = options.colWidths || [];
	this.initFunc = options.onStart || null;
	this.callbackFunc = options.onFinish || null;
	this.initFunc && this.initFunc();
	
/////* Create the framework dom */
	this.sBase = document.createElement("DIV");
	this.sFHeader = this.sBase.cloneNode(false);
	this.sHeader = this.sBase.cloneNode(false);
	this.sHeaderInner = this.sBase.cloneNode(false);
	this.sFData = this.sBase.cloneNode(false);
	this.sFDataInner = this.sBase.cloneNode(false);
	this.sData = this.sBase.cloneNode(false);
	this.sColGroup = document.createElement("COLGROUP");
	
	this.sDataTable = document.getElementById(tableId);
	this.sDataTable.style.margin = "0px"; /* Otherwise looks bad */
	if (this.cssSkin !== "") {
		this.sDataTable.className += " " + this.cssSkin;
	}
	if (this.sDataTable.getElementsByTagName("COLGROUP").length > 0) {
		this.sDataTable.removeChild(this.sDataTable.getElementsByTagName("COLGROUP")[0]); /* Making our own */
	}
	this.sParent = this.sDataTable.parentNode;
	this.sParentHeight = this.sParent.offsetHeight;
	this.sParentWidth = this.sParent.offsetWidth;
	
/////* Attach the required classNames */
	this.sBase.className = "sBase";
	this.sFHeader.className = "sFHeader";
	this.sHeader.className = "sHeader";
	this.sHeaderInner.className = "sHeaderInner";
	this.sFData.className = "sFData";
	this.sFDataInner.className = "sFDataInner";
	this.sData.className = "sData";
	
/////* Clone parts of the data table for the new header table */
	var alpha, beta, touched, clean, cleanRow, i, j, k, m, n, p;
	this.sHeaderTable = this.sDataTable.cloneNode(false);
	if (this.sDataTable.tHead) {
		alpha = this.sDataTable.tHead;
		this.sHeaderTable.appendChild(alpha.cloneNode(false));
		beta = this.sHeaderTable.tHead;
	} else {
		alpha = this.sDataTable.tBodies[0];
		this.sHeaderTable.appendChild(alpha.cloneNode(false));
		beta = this.sHeaderTable.tBodies[0];
	}
	alpha = alpha.rows;
	for (i=0; i<this.headerRows; i++) {
		beta.appendChild(alpha[i].cloneNode(true));
	}
	this.sHeaderInner.appendChild(this.sHeaderTable);
	
	if (this.fixedCols > 0) {
		this.sFHeaderTable = this.sHeaderTable.cloneNode(true);
		this.sFHeader.appendChild(this.sFHeaderTable);
		this.sFDataTable = this.sDataTable.cloneNode(true);
		this.sFDataInner.appendChild(this.sFDataTable);
	}
	
/////* Set up the colGroup */
	alpha = this.sDataTable.tBodies[0].rows;
	for (i=0, j=alpha.length; i<j; i++) {
		clean = true;
		for (k=0, m=alpha[i].cells.length; k<m; k++) {
			if (alpha[i].cells[k].colSpan !== 1 || alpha[i].cells[k].rowSpan !== 1) {
				i += alpha[i].cells[k].rowSpan - 1;
				clean = false;
				break;
			}
		}
		if (clean === true) break; /* A row with no cells of colSpan > 1 || rowSpan > 1 has been found */
	}
	cleanRow = (clean === true) ? i : 0; /* Use this row index to calculate the column widths */
	for (i=0, j=alpha[cleanRow].cells.length; i<j; i++) {
		if (i === this.colWidths.length || this.colWidths[i] === -1) {
			this.colWidths[i] = alpha[cleanRow].cells[i].offsetWidth;
		}
	}
	for (i=0, j=this.colWidths.length; i<j; i++) {
		this.sColGroup.appendChild(document.createElement("COL"));
		this.sColGroup.lastChild.setAttribute("width", this.colWidths[i]);
	}
	this.sDataTable.insertBefore(this.sColGroup.cloneNode(true), this.sDataTable.firstChild);
	this.sHeaderTable.insertBefore(this.sColGroup.cloneNode(true), this.sHeaderTable.firstChild);
	if (this.fixedCols > 0) {
		this.sFDataTable.insertBefore(this.sColGroup.cloneNode(true), this.sFDataTable.firstChild);
		this.sFHeaderTable.insertBefore(this.sColGroup.cloneNode(true), this.sFHeaderTable.firstChild);
	}
	
/////* Style the tables individually if applicable */
	if (this.cssSkin !== "") {
		this.sDataTable.className += " " + this.cssSkin + "-Main";
		this.sHeaderTable.className += " " + this.cssSkin + "-Headers";
		if (this.fixedCols > 0) {
			this.sFDataTable.className += " " + this.cssSkin + "-Fixed";
			this.sFHeaderTable.className += " " + this.cssSkin + "-FixedHeaders";
		}
	}
	
/////* Throw everything into sBase */
	if (this.fixedCols > 0) {
		this.sBase.appendChild(this.sFHeader);
	}
	this.sHeader.appendChild(this.sHeaderInner);
	this.sBase.appendChild(this.sHeader);
	if (this.fixedCols > 0) {
		this.sFData.appendChild(this.sFDataInner);
		this.sBase.appendChild(this.sFData);
	}
	this.sBase.appendChild(this.sData);
	this.sParent.insertBefore(this.sBase, this.sDataTable);
	this.sData.appendChild(this.sDataTable);
	
/////* Align the tables */
	var sDataStyles, sDataTableStyles;
	this.sHeaderHeight = this.sDataTable.tBodies[0].rows[(this.sDataTable.tHead) ? 0 : this.headerRows].offsetTop;
	sDataTableStyles = "margin-top: " + (this.sHeaderHeight * -1) + "px;";
	sDataStyles = "margin-top: " + this.sHeaderHeight + "px;";
	sDataStyles += "height: " + (this.sParentHeight - this.sHeaderHeight) + "px;";
	if (this.fixedCols > 0) {		
		/* A collapsed table's cell's offsetLeft is calculated differently (w/ or w/out border included) across broswers - adjust: */
		this.sFHeaderWidth = this.sDataTable.tBodies[0].rows[cleanRow].cells[this.fixedCols].offsetLeft;
		if (window.getComputedStyle) {
			alpha = document.defaultView;
			beta = this.sDataTable.tBodies[0].rows[0].cells[0];
			if (navigator.taintEnabled) { /* If not Safari */
				this.sFHeaderWidth += Math.ceil(parseInt(alpha.getComputedStyle(beta, null).getPropertyValue("border-right-width")) / 2);
			} else {
				this.sFHeaderWidth += parseInt(alpha.getComputedStyle(beta, null).getPropertyValue("border-right-width"));
			}
		} else if (/*@cc_on!@*/0) { /* Internet Explorer */
			alpha = this.sDataTable.tBodies[0].rows[0].cells[0];
			beta = [alpha.currentStyle["borderRightWidth"], alpha.currentStyle["borderLeftWidth"]];
			if(/px/i.test(beta[0]) && /px/i.test(beta[1])) {
				beta = [parseInt(beta[0]), parseInt(beta[1])].sort();
				this.sFHeaderWidth += Math.ceil(parseInt(beta[1]) / 2);
			}
		}
		
		/* Opera 9.5 issue - a sizeable data table may cause the document scrollbars to appear without this: */
		if (window.opera) {
			this.sFData.style.height = this.sParentHeight + "px";
		}
		
		this.sFHeader.style.width = this.sFHeaderWidth + "px";
		sDataTableStyles += "margin-left: " + (this.sFHeaderWidth * -1) + "px;";
		sDataStyles += "margin-left: " + this.sFHeaderWidth + "px;";
		sDataStyles += "width: " + (this.sParentWidth - this.sFHeaderWidth) + "px;";	    
	} else {
		sDataStyles += "width: " + this.sParentWidth + "px;";
	}
	this.sData.style.cssText = sDataStyles;
	this.sDataTable.style.cssText = sDataTableStyles;
	
/////* Set up table scrolling and IE's onunload event for garbage collection */
	(function (st) {
		if (st.fixedCols > 0) {
			st.sData.onscroll = function () {
				st.sHeaderInner.style.right = st.sData.scrollLeft + "px";
				st.sFDataInner.style.top = (st.sData.scrollTop * -1) + "px";
			};
		} else {
			st.sData.onscroll = function () {
				st.sHeaderInner.style.right = st.sData.scrollLeft + "px";
			};
		}
		if (/*@cc_on!@*/0) { /* Internet Explorer */
			window.attachEvent("onunload", function () {
				st.sData.onscroll = null;
				st = null;
			});
		}
	})(this);
	
	this.callbackFunc && this.callbackFunc();
};

 

3、superTables.css

/*
///////////////////////////////////////////////////////////////////////////////////////// 
// Super Tables v0.30 - MIT Style License
// Copyright (c) 2008 Matt Murphy --- www.matts411.com
//
// Contributors:
// Joe Gallo
///////////////////////////////////////////////////////////////////////////////////////// 
*/
.sBase {
	position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

/* HEADERS */
.sHeader {
	position: absolute;
	z-index: 3;
	background-color: #ffffff;
}
.sHeaderInner {
	position: relative;
}
.sHeaderInner table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
	background-color: #ffffff; /* Here b/c of Opera 9.25 :( */
}

/* HEADERS - FIXED */
.sFHeader {
	position: absolute;
	z-index: 4;
	overflow: hidden;
}
.sFHeader table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
	background-color: #ffffff; /* Here b/c of Opera 9.25 :( */
}

/* BODY */
.sData {
	position: absolute;
	z-index: 2;
	overflow: auto;
	background-color: #ffffff;    
}
.sData table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;
	table-layout: fixed !important;
}

/* BODY - FIXED */
.sFData {
	position: absolute;
	z-index: 1;
	background-color: #ffffff;
}
.sFDataInner {
	position: relative;
}
.sFData table {
	border-spacing: 0px 0px !important;
	border-collapse: collapse !important;
	width: 1px !important;	
	table-layout: fixed !important;
}


/*
///////////////////////////////////////////////////////////////////////////////////////// 
// Super Tables - Skin Classes
// Remove if not needed
///////////////////////////////////////////////////////////////////////////////////////// 
*/

/* sDefault */
.sDefault {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sDefault th, .sDefault td {
	border: 1px solid #cccccc;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sDefault th {
	background-color: #e5e5e5;
	border-color: #c5c5c5;
}
.sDefault-Fixed {
	background-color: #eeeeee;
	border-color: #c5c5c5;
}

/* sSky */
.sSky {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sSky th, .sSky td {
	border: 1px solid #9eb6ce;
	padding: 3px 6px 3px 4px;
	white-space: normal; /*单元格自动换行*/
}
.sSky th {
	background-color: #CFDCEE;
}
.sSky-Fixed {
	background-color: #e4ecf7;
}

/* sOrange */
.sOrange {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
}
.sOrange th, .sOrange td {
	border: 1px solid #cebb9e;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sOrange th {
	background-color: #ECD8C7;
}
.sOrange-Fixed {
	background-color: #f7ede4;
}

/* sDark */
.sDark {
	margin: 0px;
	padding: 0px;
	border: none;
	font-family: Verdana, Arial, sans serif;
	font-size: 0.8em;
	color: #ffffff;
}
.sDark th, .sDark td {
	border: 1px solid #555555;
	padding: 3px 6px 3px 4px;
	white-space: nowrap;
}
.sDark th {
	background-color: #000000;
}
.sDark-Fixed {
	background-color: #222222;
}
.sDark-Main {
	background-color: #333333;
}
.altRow {
    background-color: #ddddff;
}

 

4、调用方法参考

<script type="text/javascript">

    $(document).ready(function () {

        $(function () { /*固定表头*/

            $("#gvPMOSuggestShow").toSuperTable({

                width: "1210px",

                height: "730px",

                fixedCols: 3,

                colWidths: [30, 50, 80, 70, 60, 50, 110, 300, 250, 100, 50, 40]

            }).find("tr:even").addClass("altRow");

        });

    });

</script>

 

最后奉上文件地址:

http://download.csdn.net/detail/w19921004/8539125

 

原创文章,转载请注明: 转载自 独立观察员(dlgcy.com)

本文链接地址: [分享ASP.NET固定GridView表头的方法](https://dlgcy.com/asp-net-fix-gridview-header/)

关注微信公众号 独立观察员博客(DLGCY_BLOG) 第一时间获取最新文章

%title插图%num

目前为止有一条评论

香格里拉婚纱摄影 发布于06:46 - 2015年5月13日

沙发也是一种心情!

发表评论