[javascript] 고정 헤더가있는 HTML 테이블?

열 머리글이 화면에 고정되어 있고 표 본문으로 스크롤되지 않도록 긴 HTML 표를 표시하는 브라우저 간 CSS / JavaScript 기술이 있습니까? Microsoft Excel의 “고정 창”효과를 생각해보십시오.

테이블의 내용을 스크롤 할 수 있지만 항상 맨 위에 열 머리글을 볼 수 있기를 원합니다.



답변

나는 이것에 대한 해결책을 잠시 찾고 있었고 대부분의 답변이 작동하지 않거나 내 상황에 적합하지 않다는 것을 알았으므로 jQuery를 사용하여 간단한 솔루션을 작성했습니다.

솔루션 개요는 다음과 같습니다.

  1. 고정 헤더가 필요한 테이블을 복제하고 복제 된 사본을 원본 위에 놓으십시오.
  2. 상단 테이블에서 테이블 본체를 제거하십시오.
  3. 하단 테이블에서 테이블 헤더를 제거하십시오.
  4. 열 너비를 조정하십시오. (우리는 원래 열 너비를 추적합니다)

다음은 실행 가능한 데모의 코드입니다.

function scrolify(tblAsJQueryObject, height) {
  var oTbl = tblAsJQueryObject;

  // for very large tables you can remove the four lines below
  // and wrap the table with <div> in the mark-up and assign
  // height and overflow property  
  var oTblDiv = $("<div/>");
  oTblDiv.css('height', height);
  oTblDiv.css('overflow', 'scroll');
  oTbl.wrap(oTblDiv);

  // save original width
  oTbl.attr("data-item-original-width", oTbl.width());
  oTbl.find('thead tr td').each(function() {
    $(this).attr("data-item-original-width", $(this).width());
  });
  oTbl.find('tbody tr:eq(0) td').each(function() {
    $(this).attr("data-item-original-width", $(this).width());
  });


  // clone the original table
  var newTbl = oTbl.clone();

  // remove table header from original table
  oTbl.find('thead tr').remove();
  // remove table body from new table
  newTbl.find('tbody tr').remove();

  oTbl.parent().parent().prepend(newTbl);
  newTbl.wrap("<div/>");

  // replace ORIGINAL COLUMN width				
  newTbl.width(newTbl.attr('data-item-original-width'));
  newTbl.find('thead tr td').each(function() {
    $(this).width($(this).attr("data-item-original-width"));
  });
  oTbl.width(oTbl.attr('data-item-original-width'));
  oTbl.find('tbody tr:eq(0) td').each(function() {
    $(this).width($(this).attr("data-item-original-width"));
  });
}

$(document).ready(function() {
  scrolify($('#tblNeedsScrolling'), 160); // 160 is height
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<div style="width:300px;border:6px green solid;">
  <table border="1" width="100%" id="tblNeedsScrolling">
    <thead>
      <tr><th>Header 1</th><th>Header 2</th></tr>
    </thead>
    <tbody>
      <tr><td>row 1, cell 1</td><td>row 1, cell 2</td></tr>
      <tr><td>row 2, cell 1</td><td>row 2, cell 2</td></tr>
      <tr><td>row 3, cell 1</td><td>row 3, cell 2</td></tr>
      <tr><td>row 4, cell 1</td><td>row 4, cell 2</td></tr>
      <tr><td>row 5, cell 1</td><td>row 5, cell 2</td></tr>
      <tr><td>row 6, cell 1</td><td>row 6, cell 2</td></tr>
      <tr><td>row 7, cell 1</td><td>row 7, cell 2</td></tr>
      <tr><td>row 8, cell 1</td><td>row 8, cell 2</td></tr>
    </tbody>
  </table>
</div>

이 솔루션은 Chrome 및 IE에서 작동합니다. jQuery를 기반으로하므로 다른 jQuery 지원 브라우저에서도 작동합니다.


답변

이것은 네 줄의 코드로 깔끔하게 해결 될 수 있습니다.

최신 브라우저에만 관심이 있다면 CSS 변환을 사용하여 고정 헤더를 훨씬 쉽게 얻을 수 있습니다. 이상하게 들리지만 훌륭하게 작동합니다.

  • HTML과 CSS는 그대로 유지됩니다.
  • 외부 JavaScript 종속성이 없습니다.
  • 네 줄의 코드.
  • 모든 구성 (테이블 레이아웃 : 고정 등)에서 작동합니다.
document.getElementById("wrap").addEventListener("scroll", function(){
   var translate = "translate(0,"+this.scrollTop+"px)";
   this.querySelector("thead").style.transform = translate;
});

Internet Explorer 8을 제외하고 CSS 변환 지원이 광범위하게 제공 됩니다.

다음은 참조를위한 전체 예입니다.


답변

방금 유효한 HTML (thead 및 tbody가 있어야 함)을 사용하여 유효한 단일 테이블을 가져 와서 고정 된 머리글, 복제 된 머리글 또는 임의의 고정 바닥 글이있는 고정 바닥 글이있는 테이블을 출력하는 jQuery 플러그인 작성을 완료했습니다. 선택한 콘텐츠 (페이지 매김 등) 더 큰 모니터를 이용하려면 브라우저 크기를 조정할 때 테이블 크기도 조정됩니다. 테이블 열을 모두 볼 수없는 경우 추가 된 다른 기능으로 측면 스크롤을 수행 할 수 있습니다.

http://fixedheadertable.com/

github에서 : http://markmalek.github.com/Fixed-Header-Table/

설치가 매우 쉽고 자신 만의 스타일을 만들 수 있습니다. 또한 모든 브라우저에서 둥근 모서리를 사용합니다. 방금 발표 한 내용이므로 기술적으로 베타 버전이며 해결해야 할 사소한 문제는 거의 없습니다.

Internet Explorer 7, Internet Explorer 8, Safari, Firefox 및 Chrome에서 작동합니다.


답변

또한이 문제를 해결하는 플러그인을 만들었습니다. 내 프로젝트 -jQuery.floatThead 는 4 년 넘게 있었고 매우 성숙했습니다.

외부 스타일이 필요하지 않으며 테이블을 특정 방식으로 스타일을 지정할 필요가 없습니다. Internet Explorer9 + 및 Firefox / Chrome을 지원합니다.

현재 (2018-05)에는 다음이 있습니다.

GitHub에서 405 개의 커밋 및 998 개의 별


여기에 많은 답변이 전부는 아니지만 한 사람이 겪고있는 문제를 해결할 수있는 빠른 해킹이지만 모든 테이블에서 작동하지는 않습니다.

다른 플러그인 중 일부는 오래되었으며 Internet Explorer에서 잘 작동하지만 Firefox 및 Chrome에서는 작동하지 않습니다.


답변

TL; DR

최신 브라우저를 대상으로하고 화려한 스타일링이 필요하지 않은 경우 : http://jsfiddle.net/dPixie/byB9d/3/빅 4 버전 은 꽤 달콤하지만이 버전은 유동적 인 너비를 훨씬 더 잘 처리합니다.

모두 좋은 소식입니다!

HTML5 및 CSS3의 발전으로 이제는 최신 브라우저에서 가능합니다. 내가 생각해 낸 약간의 해시 구현은 http://jsfiddle.net/dPixie/byB9d/3/ 에서 찾을 수 있습니다 . FX 25, Chrome 31 및 IE 10에서 테스트했습니다 …

관련 HTML (문서 상단에 HTML5 문서 유형 삽입) :

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

section {
  position: relative;
  border: 1px solid #000;
  padding-top: 37px;
  background: #500;
}

section.positioned {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 800px;
  box-shadow: 0 0 15px #333;
}

.container {
  overflow-y: auto;
  height: 200px;
}

table {
  border-spacing: 0;
  width: 100%;
}

td+td {
  border-left: 1px solid #eee;
}

td,
th {
  border-bottom: 1px solid #eee;
  background: #ddd;
  color: #000;
  padding: 10px 25px;
}

th {
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  color: transparent;
  border: none;
  white-space: nowrap;
}

th div {
  position: absolute;
  background: transparent;
  color: #fff;
  padding: 9px 25px;
  top: 0;
  margin-left: -25px;
  line-height: normal;
  border-left: 1px solid #800;
}

th:first-child div {
  border: none;
}
<section class="positioned">
  <div class="container">
    <table>
      <thead>
        <tr class="header">
          <th>
            Table attribute name
            <div>Table attribute name</div>
          </th>
          <th>
            Value
            <div>Value</div>
          </th>
          <th>
            Description
            <div>Description</div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>align</td>
          <td>left, center, right</td>
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>
        </tr>
        <tr>
          <td>bgcolor</td>
          <td>rgb(x,x,x), #xxxxxx, colorname</td>
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>
        </tr>
        <tr>
          <td>border</td>
          <td>1,""</td>
          <td>Specifies whether the table cells should have borders or not</td>
        </tr>
        <tr>
          <td>cellpadding</td>
          <td>pixels</td>
          <td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>
        </tr>
        <tr>
          <td>cellspacing</td>
          <td>pixels</td>
          <td>Not supported in HTML5. Specifies the space between cells</td>
        </tr>
        <tr>
          <td>frame</td>
          <td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>
          <td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>
        </tr>
        <tr>
          <td>rules</td>
          <td>none, groups, rows, cols, all</td>
          <td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>
        </tr>
        <tr>
          <td>summary</td>
          <td>text</td>
          <td>Not supported in HTML5. Specifies a summary of the content of a table</td>
        </tr>
        <tr>
          <td>width</td>
          <td>pixels, %</td>
          <td>Not supported in HTML5. Specifies the width of a table</td>
        </tr>
      </tbody>
    </table>
  </div>
</section>

그러나 어떻게?!

간단히 표 머리글을 지정하면 0px 높이로 시각적으로 숨기고 고정 머리글로 사용되는 div가 포함됩니다. 테이블의 컨테이너는 상단에 충분한 공간을 남겨두고 절대적으로 배치 된 헤더를 허용하고 스크롤 막대가있는 테이블이 예상대로 나타납니다.

위의 코드는 배치 된 클래스를 사용하여 테이블을 절대적으로 배치합니다 (팝업 스타일 대화 상자 positioned에서 사용하고 있음). 컨테이너 에서 클래스를 제거하여 문서 흐름에서 테이블을 사용할 수 있습니다 .

그러나 …

완벽하지 않습니다. Firefox는 헤더 행을 0px로 만드는 것을 거부하지만 (적어도 나는 찾지 못했습니다) 최소한 4px로 고집스럽게 유지합니다 … 큰 문제는 아니지만 스타일에 따라 테두리 등이 엉망이됩니다.

이 테이블은 컨테이너 자체의 배경색이 헤더 div의 배경으로 사용되는 가짜 열 접근 방식을 사용합니다.

요약

요구 사항, 특히 테두리 또는 복잡한 배경에 따라 스타일 문제가있을 수 있습니다. 계산 능력에 문제가있을 수도 있지만 아직 다양한 브라우저에서 확인하지는 않았지만 (해보면 경험에 의견을 보내십시오), 나는 그와 같은 것을 찾지 못하여 게시 할 가치가 있다고 생각했습니다. 어쨌든 …


답변

CSS 사양 외부에서 이것을 해결하려는 모든 시도는 우리가 정말로 원하는 것의 창백한 그림자입니다. THEAD의 묵시적 약속에 대한 전달.

이 고정 된 표에 대한 문제는 오랫동안 HTML / CSS에서 열린 상처였습니다.

완벽한 세상에는이 문제에 대한 순수한 CSS 솔루션이 있습니다. 불행히도, 좋은 곳은없는 것 같습니다.

이 주제와 관련된 표준 토론은 다음과 같습니다.

업데이트 : Firefox position:sticky는 버전 32로 출시 되었습니다. 모두가 승리합니다!


답변

고정 테이블 헤더 용 jQuery 플러그인은 다음과 같습니다. 전체 페이지를 스크롤하여 상단에 도달하면 헤더를 고정시킵니다. Twitter Bootstrap 테이블 과 잘 작동합니다 .

GitHub 리포지토리 : https://github.com/oma/table-fixed-header

테이블 내용 만 스크롤 하지는 않습니다 . 다른 답변 중 하나로서 다른 도구를 찾으십시오. 귀하의 사례에 가장 적합한 것을 결정하십시오.