close

最近遇到要怎麼將Table的欄位凍結,後來找到只用CSS就可以做到我要的效果了!!!

Example:

先用Html寫出table並在要凍結的欄位設定style="left:0px"

<div id="tableScroll">
  <table class="table">
    <thead>
      <tr>
        <th style="left: 0px">Title1</th>
        <th style="left: 100px">Title2</th>
        <th style="left: 200px">Title3</th>
        <th style="left: 300px">Title4</th>
        <th>Title5</th>
        <th>Title6</th>
        <th>Title7</th>
        <th>Title8</th>
        <th>Title9</th>
        <th>Title10</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="left: 0px">Test1</td>
        <td style="left: 100px">Test2</td>
        <td style="left: 200px">Test3</td>
        <td style="left: 300px">Test4</td>
        <td>Test5</td>
        <td>Test6</td>
        <td>Test7</td>
        <td>Test8</td>
        <td>Test9</td>
        <td>Test10</td>
      </tr>
    </tbody>
  </table>
</div>

Css這邊我們用td:nth-child(1)選擇我們要的欄位位置

#tableScroll{
  overflow:auto;
  width:100%;
}

#tableScroll td,th {
  width: 100px;
}

#tableScroll th:not(:first-child) {
  z-index: 1;
}

#tableScroll th {
  background-color:#E2E9F1;
}

#tableScroll table {
  table-layout: fixed;
  width:100%;
}

#tableScroll td:nth-child(1), #tableScroll td:nth-child(2),
#tableScroll td:nth-child(3), #tableScroll td:nth-child(4) {
  position:sticky;
  z-index:1;
  background-color:red;
}

#tableScroll thead tr th {
  position:sticky;
  top:0;
}

#tableScroll th:nth-child(1) {
  z-index:2;
}

#tableScroll  th:nth-child(2) {
  z-index:2;
}

#tableScroll  th:nth-child(3) {
  z-index:2;
}

#tableScroll  th:nth-child(4) {
  z-index:2;
}

附上CodePen

arrow
arrow

    小小工程師林可可 發表在 痞客邦 留言(0) 人氣()