锁定表头的JS写法,支持动态宽度

<style type="text/css">

.resultDiv{

   overflow: auto;

   margin:0 0 0 1%;

   padding: 0;

}

.divW{

 border: 0;

 padding: 0;

 margin: 0;

}

.resultTable_content{

width: 100%;

border-bottom: 3px solid #999;

margin:0;

text-align: center;

line-height: 1.6em;

border-collapse: collapse;

background: #fff;

word-wrap: break-word; word-break: break-all;

padding:0;

}

.resultTable_title {

    width: 100%;

    margin:0;

border-bottom: 0;

text-align: center;

line-height: 1.6em;

border-collapse: collapse;

background: #fff;

word-wrap: break-word; word-break: break-all;

padding:0;

}

.resultTable_content td,.resultTable_title td {

border: 1px solid #8C8C8C;

white-space: nowrap;

padding:2px;

margin: 0;

}

.resultTable_content th,.resultTable_title th {

    border: 1px solid #8C8C8C;

font-weight: bold;

text-align: center;

white-space: nowrap;

padding:2px;

margin: 0;

}

.scrollDivT {

overflow:auto;

margin: 0;

padding: 0;

border:0;

}

</style>

<script type="text/javascript">

attachListener(window,"load",function(){ addScrollBar2();},false);

var log;

var version = "1.0.2";

/**

  * adjust table height.

  */

var SCROLL_CSS_RESULT_TABLE_CONTENT = 'resultTable_content';

var SCROLL_CSS_RESULT_TABLE_TITLE = 'resultTable_title';

//var SCROLL_CSS_RESULT_TABLE_TITLE = 'viewItemTable';

var SCROLL_CLASS_NAME_T = "scrollDivT";

var rowHeight = 24;

var rowHeader = 25;

var navigatorHeight = 25;

var minHeight = rowHeader * 2;

var contentW = null;

var IE = (!!(window.attachEvent && !window.opera));

var FF = (navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1);

var w3c=(document.getElementById)? true:false;

var ns6=(w3c && (navigator.appName=="Netscape"))? true: false;

var scrollBarIndex = 0; //for id of div

/**

  *  table attribute :

  *  1. maxRows - 0|null -> 30, n -> when actual rows exceeding maxRows,maxRows visible,

  *     other rows can be viewed by scroll. when actual rows is less than maxRows, maxRows displayed with some empty rows. 

  *     when you set autoAdjustHeight = true, system could display actual row count.

  *  

  *  2. autoAdjustHeight - default (true )

  *  3. maxRows - default (null)

  *  

  */ 

function addScrollBar2(){

  //in IE, setting attribute overflow could raise window.onresize event 

  document.documentElement.style.overflow="hidden";

  

  fireForEachClass2(SCROLL_CSS_RESULT_TABLE_CONTENT+","+SCROLL_CSS_RESULT_TABLE_TITLE,scrollProcessor2,"TABLE");

  //IE bug fix!!!

  //document.documentElement.style.overflow="auto";

  //---------------------------------------------

  //setTimeout('addWindowOnResizeHandler2()',2000);

}

function addWindowOnResizeHandler2(){

  

  //window.onresize = function(evt){

    fireForEachClass2(SCROLL_CSS_RESULT_TABLE_CONTENT+","+SCROLL_CSS_RESULT_TABLE_TITLE,resizeProcessor2,"TABLE");

  //}

}

/**

  * @param tblCtrl -> table object or id

  * @return divObj 

  */

function preHandleTable2(tblCtrl){

    

  if (tblCtrl == null){

    log && log.debug("[preHandleTable]tblCtrl is null","white","red");

    return null;

  }

  if (typeof tblCtrl == "string"){

    tblCtrl = document.getElementById(tblCtrl);

  }

  if (tblCtrl == null || tblCtrl.tagName != "TABLE"){

log && log.error("[preHandleTable]invalid table ->"+tblCtrl);

return null;

  }

  //for IE: get all checkboxes in container,save checked ctrl.

  if (IE){

  var allChecked = [];

  var checkboxes = tblCtrl.getElementsByTagName("INPUT");

  for (var i=0;i<checkboxes.length;i++){

    if (checkboxes[i].type=="checkbox" && checkboxes[i].checked){

      allChecked.push(checkboxes[i]);

    }

  }

  log && log.debug("[preHandleTable]checked count->"+allChecked.length);

}

  //-----------------------------------------------------------

  var divObj=document.createElement('Div');

  divObj.className=SCROLL_CLASS_NAME_T;     

  divObj.id = "SBr"+(scrollBarIndex++);

  //divObj.style.border="1px solid blue";

  var tempObj=document.createElement('Div');

  tempObj.style.width='1px';

  tempObj.style.height='1px';

  tempObj.id = "SBr"+(scrollBarIndex++);

  tblCtrl.parentNode.replaceChild(divObj,tblCtrl);    

  divObj.appendChild(tblCtrl);

  divObj.appendChild(tempObj);

if (IE){

  // restore checked status of checkboxes ---------------------

  log && log.debug("[preHandleTable]checked count->"+allChecked.length);

  var chk = null;

  var count = allChecked.length;

  for (var i=0;i<count;i++){

    chk = allChecked.pop();

    chk.checked = true;

    log && log.debug("[preHandleTable]"+i+" is pop() && checked");

  }

}

  //----------------------------------------------------------

  return divObj;

}

function scrollProcessor2(item,index,totalCount){

log && log.debug("scrollProcessor fired","green","white");

  var divObj = preHandleTable2(item);

  if (divObj == null){

  return;

  }

resizeProcessor2(item,index,totalCount);  

}

/**

  * @item

  */

function resizeProcessor2(item,index,totalCount){

    var divObj = item.parentNode;

  if (divObj == null){

  log && log.error("[resizeProcessor] could not find divObj");

  return;

  }

  

  var tableCtrl = item ;

  if (tableCtrl.style.display=="none"){

  log && log.debug("[adjustCommonTableHeight]tableCtrl is invisible , ignore");

    return;

  }

  if (tableCtrl == null || tableCtrl.tagName !="TABLE"){

  log && log.error("[adjustCommonTableHeight]invalid tableCtrl->"+tableCtrl);

  return;

  }

  

  //---------------------- maxRows , autoAdjustHeight ----------------------------

  var maxRows = null;

  var autoAdjustHeight = null;

  maxRows = tableCtrl.getAttribute("maxRows");

  autoAdjustHeight = ("true"==tableCtrl.getAttribute("autoAdjustHeight") || true);

  if (isNaN(maxRows) || maxRows == null){

    maxRows = null;

  }

  //------------------------------------------------------------------------------

    if (tableCtrl.className == SCROLL_CSS_RESULT_TABLE_CONTENT){

      adjustLastTableHeight2(divObj,tableCtrl,autoAdjustHeight,maxRows);

    }else{    

      adjustCommonTableHeight2(divObj,tableCtrl,autoAdjustHeight,maxRows);

    } 

//动态计算宽度

//每一个单元格需要设置宽度

    var cTr = $("."+SCROLL_CSS_RESULT_TABLE_CONTENT).find("tr:first");

    var cTdArray = $(cTr).find("td");

    if(cTdArray.length==1){

    return;

    }

    var hThArray = [];

   

    var realThCol = $("."+SCROLL_CSS_RESULT_TABLE_TITLE).attr('realThCol');

        for(var i=1;i<=realThCol;i++){

        var $realThArray = $("."+SCROLL_CSS_RESULT_TABLE_TITLE).find(".realTh"+i);

        $.merge( hThArray, $realThArray);

        }

        if(tableCtrl.className==SCROLL_CSS_RESULT_TABLE_CONTENT){

    $.each(cTdArray,function(i,n){

    var width = 0;

    if($(hThArray[i]).width()<$(this).width()){

    width = $(this).width();

    }else{

    width = $(hThArray[i]).width();

    }

    var divs = $(this).find('.divW');

    if(divs.length==0){

    $(this).html('<div class="divW">'+$(this).html()+'</div>');

    $(hThArray[i]).html('<div class="divW">'+$(hThArray[i]).html()+'</div>');

   

    }

    $(this).find('.divW:eq(0)').width(width+4);

$(hThArray[i]).find('.divW:eq(0)').width(width+4); //这里是关键,其实因为字体的问题会导致单元格实际宽度不对,那么要适当增大div的宽度,可以使单元格完美对齐

   

    });

        }

    if(tableCtrl.className==SCROLL_CSS_RESULT_TABLE_CONTENT){

       contentW = $('.'+SCROLL_CSS_RESULT_TABLE_CONTENT).outerWidth();

       divObj.style.width = contentW+30;

    }else if(tableCtrl.className==SCROLL_CSS_RESULT_TABLE_TITLE){

       divObj.style.width = contentW+13;

    }

  

}

/**

  * @author fisher zhang on 2008.8.12 19:14

  * @param 

  */

function getRect2(obj){

  var rect={"left":0,"top":0,"width":0,"height":0};

  var lt = GetLT(obj);

  rect.left= lt.offsetLeft;

  rect.top = lt.offsetTop;

  rect.width=obj.offsetWidth;

  rect.height=obj.offsetHeight;

  return rect;

}

 function GetLT2(obj){

var LT = {"offsetLeft":0,"offsetTop":0};

 var nLt=0;

 var nTp=0;

  var offsetParent = obj;

  while (offsetParent!=null && offsetParent!=document.body) {

   nLt+=offsetParent.offsetLeft;

   nTp+=offsetParent.offsetTop;

   if(!ns6){

   nLt+= parseInt(offsetParent.currentStyle.borderLeftWidth)>0?parseInt(offsetParent.currentStyle.borderLeftWidth):0;

   nTp+=parseInt(offsetParent.currentStyle.borderTopWidth)>0?parseInt(offsetParent.currentStyle.borderTopWidth):0;

   }

   offsetParent = offsetParent.offsetParent;

  }

  LT.offsetLeft = nLt;

  LT.offsetTop =  nTp;

  return LT;

 } 

  

/** @author fisher zhang on 2009.3.10 21:02

  * 

  */

function getClientHeight2(){

  return document.body.clientHeight||document.documentElement.clientHeight;

}

function getPageActualHeight2(){

/*

  if(IE){

    actualHeight = document.body.scrollHeight;

  }else if (FF){

    actualHeight = document.body.offsetHeight;

  }

  */

return document.body.scrollHeight;

}

/**

  * only one table in page.

  * C-------------------------------------| P

  * L|                                    | A

  * I|                                    | G

  * E|                                    | E

  * N|                                    |

  * T|  |------------------------------|  |

  *  |  |                              |  |

  * H|  |                              |  |

  *  ---|------------------------------|--| H

  *  |  |                              |  | E

  *  |  |                              |  | I

  *  |  --------------------------------  | G

  *  |                                    | H

  *  -------------------------------------| T

  *

  * C-------------------------------------| P

  * L|                                    | A

  * I|                                    | G

  * E|                                    | E

  * N|                                    |

  * T|  |------------------------------|  |

  *  |  |                              |  |

  * H|  |------------------------------|  |

  *  -------------------------------------| H

  *  |                                    | E

  *  |                                    | I

  *  |                                    | G

  *  |                                    | H

  *  -------------------------------------| T

  */

function adjustLastTableHeight2(divObj,tableCtrl,autoAdjustHeight,maxRows){

  

  //do not use getRect(tableCtrl), because offsetHeight of tableCtrl is fixed.

  var divRect=getRect2(divObj);

  var pageActualH = getPageActualHeight2();

  var clientH = getClientHeight2();

log && log.debug("[adjustLastTableHeight]dH->"+divRect.height+",dT->"+divRect.top);

  if (maxRows != null && divRect.height > rowHeader+rowHeight*maxRows){

  divObj.style.height = rowHeader+rowHeight*maxRows;

  log && log.debug("[adjustLastTableHeight]divRect.height->"+divRect.height+",rowHeader+rowHeight*maxRows->"+(rowHeader+rowHeight*maxRows),"green","yellow");

  }else{

  var footerH = navigatorHeight;

  var actualH = clientH - divRect.top - footerH;

  divObj.style.height =  (actualH > minHeight ? actualH : minHeight);

  log && log.debug("[adjustLastTableHeight]pH->"+pageActualH+",cH->"+clientH+",fH->"+footerH+",dH->"+divRect.height+",aH->"+divObj.style.height,"green","yellow");

  }

}

/**

  * @author fisher zhang on 2008.8.12 

  * we need adjust height of table manually.

  * @param divObj -> div object

  */

function adjustCommonTableHeight2(divObj,tableCtrl,autoAdjustHeight,maxRows){

  

  var divRect=getRect2(divObj);

  

  log && log.warn("divRect.height->"+divRect.height+",rowHeader+rowHeight*maxRows->"+(rowHeader+rowHeight*maxRows));

  if (maxRows!= null && divRect.height > rowHeader+rowHeight*maxRows){

    divObj.style.height = rowHeader+rowHeight*maxRows;

  }else{

    if (autoAdjustHeight == true){

      // we need not to set height of div because of the attribute autoAdjustHeight is set.

    }else{

      divObj.style.height = rowHeader+rowHeight*maxRows;

    } 

  }

}

/** @param classNames single className or classNames with , separator

  * @param callbackFunc - callbackFunc(item,index,totalCount)

  * @param tagName - TABLE ,... 

  */

function fireForEachClass2(clazzNames,callbackFunc,tagName){

  if (clazzNames == null){

  return;

  }

  var _classNames = [];

  if (clazzNames.indexOf(",")!=-1){

  var tmpNames = clazzNames.split(",");

  for (var i=0;i<tmpNames.length;i++){

  _classNames.push(tmpNames[i]);

  }

  }else{ //only one className

  _classNames.push(clazzNames);

  }

  var dstContainers = new Array();

  $.each(_classNames,function(i,n){

  if($('table.'+n).length>0){

  dstContainers.push($('table.'+n).get(0));

  }

  });

  

  for (var i=0;i<dstContainers.length;i++){

      container = dstContainers[i];

      if (callbackFunc){ callbackFunc(container,i,dstContainers.length); }      

  }

   

}

</script>

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值