简体   繁体   English

滚动时修复了 html 表 header

[英]Fixed html table header while scrolling

I have the following table structure:我有以下表结构:

<table>   
<thead>   
    <tr>   
        <th colspan="4">Current</th>   
        <th colspan="4">New/Requested</th>   
    </tr>   
    <tr>   
        <th nowrap="nowrap">RSD &nbsp;&nbsp;&nbsp;&nbsp;</th>  
        <th nowrap="nowrap">CRSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">MSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">Open QTY &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">CRD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">CRSD &nbsp;&nbsp;&nbsp;&nbsp;</th>  
        <th nowrap="nowrap">MSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">Open QTY &nbsp;&nbsp;&nbsp;&nbsp;</th>   
        <th nowrap="nowrap">Action</th>   
        <th nowrap="nowrap">Reason</th>   
        <th nowrap="nowrap">Action Code Status </th>   
    </tr> 
    <tbody>
        <tr>
            <td></td>  
            <td></td>   
            .....plenty of rows
        </tr>
    </tbody>
</thead>   
</table> 

I am trying to fix the header so that if I scroll down it stays visible.我正在尝试修复 header 以便如果我向下滚动它仍然可见。 I looked at this post but couldn't understand it.我看了这篇文章,但无法理解。 How can I do this?我怎样才能做到这一点?

I have written the following code in order to achieve my goal (as asked in question)-我编写了以下代码以实现我的目标(如问题所述)-

Here is the plugin i have written.这是我写的插件。

(function ($) {
   $.fn.scrollbarTable = function (i) {
       var o = {};
       if (typeof (i) == 'number') o.height = i;
       else if (typeof (i) == 'object') o = i;
       else if (typeof (i) == 'undefined') o = {
           height: 300
       }
       return this.each(function () {
           var $t = $(this);
           var w = $t.width();
           $t.width(w - function (width) {
               var parent, child;
               if (width === undefined) {
                   parent = $('<div style="width:50px;height:50px;overflow:auto"><div style="height:50px;"></div></div>').appendTo('body');
                   child = parent.children();
                   width = child.innerWidth() - child.height(99).innerWidth();
                   parent.remove();
               }
               return width;
           }());
           var cols = [];
           var tableCols = [];
           $t.find('thead th,thead td').each(function () {
               cols.push($(this).width());
           });
           $t.find('tr:eq(1) th,thead td').each(function () {
               tableCols.push($(this).width());
           });
           var $firstRow = $t.clone();
           $firstRow.find('tbody').remove();
           $t.find('thead').remove();
           $t.before($firstRow);
           $firstRow.find('thead th,thead td').each(function (i) {
               $(this).attr('width', cols[i]);
           });
           $t.find('tr:first th,tr:first td').each(function (i) {
               $(this).attr('width', tableCols[i]);
           });
           var $wrap = $('<div>');
           $wrap.css({
               width: w,
               height: o.height,
               overflow: 'auto'
           });
           $t.wrap($wrap);
       })
   };
}(jQuery));

How to use:如何使用:

$(document).ready(function(){
    $('table#tabss').scrollbarTable();
}

hope it will help someone somewhere..希望它会帮助某个地方的人..

Any way thanks to all of you for your kind support... :)无论如何感谢大家的支持... :)

I know that I'm late to the party, but the jQuery Fixed Table Header Plugin by Mustafa OZCAN is fantastic.我知道我迟到了,但是 Mustafa OZCAN 的jQuery 固定表 Header 插件非常棒。 Just include it, as well as jQuery itself, and set it to work on your table like so:只需包含它,以及 jQuery 本身,并将其设置为在您的桌子上工作,如下所示:

<script type="text/javascript"> 
$(document).ready(function() { 
   $('#YourTable').fixedtableheader(); 
}); 
</script>

Replace #YourTable with the ID of your HTML table, and the plugin does the rest.#YourTable替换为 HTML 表的 ID,插件执行 rest。

Alas, how I envy people who get to use jQuery.唉,我多么羡慕那些开始使用 jQuery 的人。 I created a pure javascript and CSS solution for those who are prevented by application limitations from loading a library.我为那些因应用程序限制而无法加载库的人创建了一个纯 javascript 和 CSS 解决方案。

Basically, CSS positions the table and table header row, and tricks the table into behaving like divs.基本上,CSS 定位表和表 header 行,并欺骗表表现得像 div。 Then javascript manipulates the CSS positioning of the table header row and a "mask" div that hides the moving rows as the table scrolls up (an improvement would be to modify the javascript to detect collision and hide rows that scroll up past the header). Then javascript manipulates the CSS positioning of the table header row and a "mask" div that hides the moving rows as the table scrolls up (an improvement would be to modify the javascript to detect collision and hide rows that scroll up past the header).

The weakness of this approach is that you now have to set the widths for all the columns.这种方法的缺点是您现在必须设置所有列的宽度。

The relevant components are:相关组件是:

<!-- divs with IDs are manipulated with javascript -->
<div class="fixedTableHolder">

  <div class="maskHolder">
     <div id="mask" class="mask">&nbsp;</mask>
  </div>

  <div class="fixedTable">
    <div id="theTable" class="theTable">

       <!-- here is the table, header row must have an ID -->
       <table border="0" cellspacing="5" cellpadding="5"> 
          <tr id="thFixed" class="thFixed"> 
            <td class="col1">Header cell 1</td> 
          </tr>
          <tr>
            <td class="col1">regular cell</td>
          </tr>
       </table>
    </div>
  </div>
</div>

Here is a demo in jsFiddle: http://jsfiddle.net/deborah/Msvvr/这是 jsFiddle 中的演示: http://jsfiddle.net/deborah/Msvvr/

Well, hoping someone will be reading this, and save some time with it:) My goal was to make a small(as small as possible) js, that will take tableID, and put headers as fixed.好吧,希望有人会阅读这篇文章,并节省一些时间:) 我的目标是制作一个小(尽可能小)的 js,它将采用 tableID,并将标题设置为固定。 It differs from what is given here with that it recalculates width with window.resize, so it allows tables to be resized dynamically, and no fixed sizes used from the start.它与此处给出的不同之处在于它使用 window.resize 重新计算宽度,因此它允许动态调整表格大小,并且从一开始就没有使用固定大小。 And in theory - suppose to work with any table... (that was my case...)理论上 - 假设可以使用任何表格......(这是我的情况......)

function HeadsUp()
{
    var headers = $("#TheGrid tr").first();
    headers.css("margin-top", ((headers.height()+1)*-1)+"px");//edit +1 with what you want...
    headers.css("position", "absolute");
}

function ResizeHeaders()
{
    var grid = $("#TheGrid");
    var headers = $("#TheGrid tr").first();
    var firstdatarow = $("#TheGrid tr:nth-child(2)");
    headers.width(grid.width());

    var s = firstdatarow.children("td");
    var d = headers.children("th");//replace with td if you use it there
    for(i=0; i<s.length; i+=1) {
        d[i].width = s[i].clientWidth;
    }
}

$(function () {
HeadsUp();
ResizeHeaders();
});

$( window ).resize(function() {
ResizeHeaders();
});

The best option which worked for me is adding the following css properties to the th class in stylesheet.对我有用的最佳选择是将以下 css 属性添加到样式表中的class 中。

th 
{
position: -webkit-sticky;
position: sticky;
top: 0px;
z-index: 5;
}

try this approach but it may not be the best way尝试这种方法,但它可能不是最好的方法

<table style="top: 0px; position: fixed; z-index: 1; background-color: White">   
    <tr>   
      <th colspan="4">Current</th>   
      <th colspan="4">New/Requested</th>   
    </tr>    
    <tr>   
    <th nowrap="nowrap">RSD &nbsp;&nbsp;&nbsp;&nbsp;</th>  
    <th nowrap="nowrap">CRSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">MSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">Open QTY &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">CRD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">CRSD &nbsp;&nbsp;&nbsp;&nbsp;</th>  
    <th nowrap="nowrap">MSD &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">Open QTY &nbsp;&nbsp;&nbsp;&nbsp;</th>   
    <th nowrap="nowrap">Action</th>   
    <th nowrap="nowrap">Reason</th>   
    <th nowrap="nowrap">Action Code Status </th>   
</tr> 
</table>
<table>
   <tbody>
      <tr>
        <td></td>  
        <td></td>   
        .....plenty of rows
      </tr>
   </tbody>
 </table>

what I did is just created another table for header and gave it fixed position我所做的只是为 header 创建了另一个表并修复了 position

Using css使用 css

.fixhead
{ 
    position:relative
    overflow:auto;
}

And call this class in or in gridview headerrowstyle tag.并在 gridview headerrowstyle 标记中或中调用此 class。

CSS PART---- CSS零件----

 <style type="text/css">
    thead tr { position:relative; 
               top: expression(offsetParent.scrollTop); 
             }

  </style>

HTML PART---- HTML PART----

<table width="100%" border="0" cellpadding="0" cellspacing="0" align="center">
    <thead>
     <tr>
      <td width="1%"></td>
      <td>ID</td>
      <td>Name</td>
     </tr>
    </thead>
    <tbody>
    //////////code
    </tbody>
    <tfoot>
    ////////code
    </tfott>
  </table>

Thanks谢谢

Set overflow: auto in the tbody's css.在 tbody 的 css 中设置溢出:auto。

so I had to create a similar component for my work.所以我不得不为我的工作创建一个类似的组件。 ( Note: admittedly I did this with jQuery but it can still be accomplished without it.) 注意:诚然,我是用 jQuery 做到的,但没有它仍然可以完成。)

The solution i came up with was similar and i thought i'd share it as it is much simplier我想出的解决方案是相似的,我想我会分享它,因为它更简单

http://jsfiddle.net/YYaFr/6/ http://jsfiddle.net/YYaFr/6/

Basically you wrap the table in a div , copy it (the table) and make the first one just a header table (by removing the tbody ) and position it absolute.基本上,您将table包装在div中,复制它(表格)并将第一个表格制作为 header 表格(通过删除tbody )和 position 它是绝对的。

<div class="containerdiv">
    <table class="headerTable">
        <colgroup>
            <col /> * number of columns
             ....
        </colgroup>
        <thead>
             <th></th>
             ....
        </thead>
    </table>
    <table class="dataTable">
        <colgroup>
            <col /> * number of columns
             ....
        </colgroup>
        <thead>
             <th></th>
             ....
        </thead>
        <tbody>
             <td></td>
             ....
        </tbody>
    </table>
</div>

and the css和 css

div.containerDiv
{
    height: 300px; // Whatever height you need. can be set inline if you wish
}
div.containerDiv table.headerTable
{
    position: absolute;
}
div.containerDiv table.dataTable thead
{
    visibility: hidden; // This gives the header table room so it doesn't hide the first row.
}

Then the JavaScript basically creates the colgroups (or you can generate them server-side if you need.) Sets the widths and viola.然后 JavaScript 基本上创建了colgroups (或者如果需要,您可以在服务器端生成它们。)设置宽度和中提琴。 That seems a lot simpler in my head so go ahead and check out the jsfiddle.在我看来,这似乎要简单得多,所以前面的 go 并查看 jsfiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM