日期:2014-05-18 浏览次数:20571 次
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>JavaScript Table行定位效果</title> <script type="text/javascript" src="CJL.0.1.min.js"></script> <script> var TableFixed = function(table, options){ this._oTable = $$(table);//原table this._nTable = this._oTable.cloneNode(false);//新table this._nTable.id = "";//避免id冲突 this._oTablePos = {};//记录原table坐标参数 this._oRowPos = {};//记录原tr坐标参数 this._viewHeight = this._oTableHeight = this._nTableHeight = 0;//记录高度 this._nTableViewTop = 0;//记录新table视框top this._selects = [];//select集合,用于ie6覆盖select this._setOptions(options); this._index = this.options.index; this._pos = this.options.pos; this.auto = !!this.options.auto; this.hide = !!this.options.hide; $$E.addEvent(window, "resize", $$F.bind( this.setPos, this )); $$E.addEvent(window, "scroll", $$F.bind( this.run, this )); this._oTable.parentNode.insertBefore(this._nTable, this._oTable); this.clone(); }; TableFixed.prototype = { //chrome/safari透明用rgba(0, 0, 0, 0) _transparent: $$B.chrome || $$B.safari ? "rgba(0, 0, 0, 0)" : "transparent", //设置默认属性 _setOptions: function(options) { this.options = {//默认值 index: 0,//tr索引 auto: true,//是否自动定位 pos: 0,//自定义定位位置百分比(0到1) hide: false//是否隐藏(不显示) }; $$.extend(this.options, options || {}); }, //克隆表格 clone: function(index) { //设置table样式 $$D.setStyle(this._nTable, { width: this._oTable.offsetWidth + "px", position: $$B.ie6 ? "absolute" : "fixed", zIndex: 99, borderTopWidth: 0, borderBottomWidth: 0 }); //设置index this._index = Math.max(0, Math.min(this._oTable.rows.length - 1, isNaN(index) ? this._index : index)); //克隆新行 this._oRow = this._oTable.rows[this._index]; var oT = this._oRow, nT = oT.cloneNode(true); if( oT.parentNode != this._oTable ){ nT = oT.parentNode.cloneNode(false).appendChild(nT).parentNode; } //插入新行 if ( this._nTable.firstChild ) { this._nTable.replaceChild( nT, this._nTable.firstChild ); } else { this._nTable.appendChild(nT); } //去掉table上面和下面的边框 if ( this._oTable.border > 0 ) { switch (this._oTable.frame) { case "above" : case "below" : case "hsides" : this._nTable.frame = "void"; break; case "" : case "border" : case "box" : this._nTable.frame = "vsides"; break; } } //设置td样式 var nTds = this._nTable.rows[0].cells, getStyle = $$D.getStyle; $$A.forEach(this._oRow.cells, $$F.bind(function(o, i){ var style = nTds[i].style; //设置td背景 style.backgroundColor = this._getBgColor(o); //设置td的width,没考虑ie8/chrome设scroll的情况 style.width = (document.defaultView ? parseFloat(getStyle(o, "width")) : ( o.clientWidth - parseInt(getStyle(o, "paddingLeft")) - parseInt(getStyle(o, "paddingRight")) )) + "px"; }, this)); //获取table高度 this._oTableHeight = this._oTable.offsetHeight; this._nTableHeight = this._nTable.offsetHeight; //设置坐标属性 this._oTablePos = $$D.rect(this._oTable);//获取原table位置 th