Исправлен заголовок HTML-таблицы при прокрутке - PullRequest
8 голосов
/ 30 июня 2011

У меня следующая структура таблицы:

<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> 

Я пытаюсь исправить заголовок, чтобы при прокрутке вниз он оставался видимым.Я посмотрел на этот пост , но не смог этого понять.Как я могу это сделать?

Ответы [ 10 ]

5 голосов
/ 06 июля 2011

Я написал следующий код для достижения своей цели (как задано в вопросе) -

Вот плагин, который я написал.

(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));

Как использовать:

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

надеюсь, что это поможет кому-то где-то ..

В любом случае спасибо всем вам заВаша поддержка ...:)

0 голосов
/ 15 октября 2018

Лучший вариант, который сработал для меня, - это добавить следующие свойства css в класс th в таблице стилей.

th 
{
position: -webkit-sticky;
position: sticky;
top: 0px;
z-index: 5;
}
0 голосов
/ 18 сентября 2013

Что ж, надеясь, что кто-то прочтет это и сэкономит некоторое время вместе с этим :) Моя цель состояла в том, чтобы сделать небольшой (как можно меньше) js, который будет принимать tableID и устанавливать фиксированные заголовки.Он отличается от того, что приведено здесь, тем, что пересчитывает ширину с помощью window.resize, поэтому он позволяет динамически изменять размеры таблиц и не использовать фиксированные размеры с самого начала.А в теории - предположим, работать с любой таблицей ... (это был мой случай ...)

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();
});
0 голосов
/ 11 апреля 2013

Увы, как я завидую людям, которые используют jQuery. Я создал чистое решение для JavaScript и CSS для тех, кто не может загружать библиотеку из-за ограничений приложения.

По сути, CSS позиционирует таблицу и строку заголовка таблицы и обманывает таблицу, ведя себя как div. Затем javascript манипулирует позиционированием CSS строки заголовка таблицы и «маскирующим» дивом, который скрывает движущиеся строки при прокрутке таблицы вверх (улучшением было бы изменение javascript для обнаружения коллизий и скрытия строк, которые прокручиваются выше заголовка).

Слабость этого подхода в том, что теперь вам нужно установить ширину для всех столбцов.

Соответствующие компоненты:

<!-- 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>

Вот демоверсия в jsFiddle: http://jsfiddle.net/deborah/Msvvr/

0 голосов
/ 14 августа 2012

Я знаю, что опаздываю на вечеринку, но плагин фиксированной таблицы jQuery от Mustafa OZCAN - это фантастика. Просто включите его, а также сам jQuery, и настройте его для работы на вашем столе так:

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

Замените #YourTable идентификатором вашей HTML-таблицы, а плагин сделает все остальное.

0 голосов
/ 16 августа 2011

поэтому мне пришлось создать аналогичный компонент для моей работы. ( Примечание: по общему признанию, я сделал это с jQuery, но это все еще может быть достигнуто без него.)

Решение, которое я придумал, было похожим, и я подумал, что поделюсь им, поскольку оно намного проще

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

По сути, вы оборачиваете table в div, копируете его (таблицу) и делаете первый просто таблицей заголовков (удаляя tbody) и позиционируете его как абсолютное.

<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>

и КСС

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.
}

Затем JavaScript в основном создает colgroups (или вы можете сгенерировать их на стороне сервера, если вам нужно.) Устанавливает ширину и альт. В моей голове это кажется намного проще, так что давай проверим jsfiddle.

0 голосов
/ 13 августа 2011

Установить переполнение: авто в css.

0 голосов
/ 30 июня 2011

ЧАСТЬ CSS ----

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

  </style>

ЧАСТЬ HTML ----

<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>

Спасибо

0 голосов
/ 30 июня 2011

Использование css

.fixhead
{ 
    position:relative
    overflow:auto;
}

И вызов этого класса в или в теге gridrow headerrowstyle.

0 голосов
/ 30 июня 2011

попробуйте этот подход, но это может быть не лучшим способом

<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>

я просто создал еще одну таблицу для заголовка и присвоил ей фиксированную позицию

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...