<div class='table-container'>
  <table class='table'>
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
        <td>Row 1, Column 3</td>
      </tr>
      <tr>
        <td>Row 2, Column 1</td>
        <td>Row 2, Column 2</td>
        <td>Row 2, Column 3</td>
      </tr>
      ...
    </tbody>
  </table>
</div>
<style>
.table-container {
  overflow-x: auto;
  max-width: 100%;
  position: relative;
}

.table {
  width: max-content;
}

thead th {
  position: sticky;
  top: 0;
  background: #fff;
}
</style>
<h2>使用 JavaScript 实现表头跟随滚动条滚动</h2>
<div class='table-container'>
  <table class='table'>
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Row 1, Column 1</td>
        <td>Row 1, Column 2</td>
        <td>Row 1, Column 3</td>
      </tr>
      <tr>
        <td>Row 2, Column 1</td>
        <td>Row 2, Column 2</td>
        <td>Row 2, Column 3</td>
      </tr>
      ...
    </tbody>
  </table>
</div>
<script>
const tableContainer = document.querySelector('.table-container');
const table = document.querySelector('.table');
const tableHeader = table.querySelector('thead');

tableContainer.addEventListener('scroll', () => {
  tableHeader.style.transform = `translateY(${tableContainer.scrollTop}px)`;
});
</script>
Laravel DCA-Admin Grid 表格表头固定实现方法

原文地址: https://www.cveoy.top/t/topic/nj4d 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录