HTML 테이블 스크롤 틀 고정

1 개요[ | ]

floating-thead
persistent thead when scroll down
HTML 테이블 스크롤 틀 고정
<style>
table { border-collapse: collapse; }
th { background: #cdefff; height: 32px; }
th, td { border: 1px solid silver; padding:5px; }
</style>

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function () {
  $('table.floating-thead>thead').each(function() {
    $(this).after( $(this).clone().hide().css('top',0).css('position','fixed') );
  });
  
  $(window).scroll(function() {
    $('table.floating-thead').each(function(i) {
      var table = $(this),
        thead = table.find('thead:first'),
        clone = table.find('thead:last'),
        top = table.offset().top,
        bottom = top + table.height() - thead.height(),
		left = table.position().left,
		border = parseInt(thead.find('th:first').css('border-width')),
        scroll = $(window).scrollTop();
      
      if( scroll < top || scroll > bottom ) {
        clone.hide();
        return true;
      }
      if( clone.is('visible') ) return true;
      clone.css('left',left).show().find('th').each(function(i) {
        $(this).width( thead.find('th').eq(i).width() + border );
      });     
    });
  });
});
</script>

<h1>표 1</h1>
<table class='floating-thead'>
  <thead>
    <tr><th>#</th><th>No.</th><th>Name</th></tr>
  </thead>
  <tbody>
    <tr><td>1</td><td>Alice</td><td>앨리스</td></tr>
    <tr><td>2</td><td>Bob</td><td></td></tr>
    <tr><td>3</td><td>Carol</td><td>캐롤</td></tr>
    <tr><td>4</td><td>Dan</td><td></td></tr>
    <tr><td>5</td><td>Erin</td><td>어린</td></tr>
    <tr><td>6</td><td>Frank</td><td>프랭크</td></tr>
    <tr><td>7</td><td>Green</td><td>그린</td></tr>
    <tr><td>8</td><td>Honey</td><td>허니</td></tr>
    <tr><td>9</td><td>Isabella</td><td>이사벨라</td></tr>
    <tr><td>10</td><td>John</td><td></td></tr>
  </tbody>
</table>

<h1>표 2</h1>
<table class='floating-thead' style='width:100%'>
  <thead>
    <tr><th>test</th><th>번호</th><th>이름</th></tr>
  </thead>
  <tbody>
    <tr><td>Hello World</td><td>1</td><td>한놈</td></tr>
    <tr><td>Hello World</td><td>2</td><td>두시기</td></tr>
    <tr><td>Hello World</td><td>3</td><td>석삼</td></tr>
    <tr><td>Hello World</td><td>4</td><td>너구리</td></tr>
    <tr><td>Hello World</td><td>5</td><td>오징어</td></tr>
    <tr><td>Hello World</td><td>6</td><td>한놈</td></tr>
    <tr><td>Hello World</td><td>7</td><td>두시기</td></tr>
    <tr><td>Hello World</td><td>8</td><td>석삼</td></tr>
    <tr><td>Hello World</td><td>9</td><td>너구리</td></tr>
    <tr><td>Hello World</td><td>10</td><td>오징어</td></tr>
  </tbody>
</table>

<br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br>

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}