萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現雙 Table 固定表頭同步滾動與自適應佈局

需求場景

資料表格需固定表頭,內容區域可垂直/水平滾動,且表頭與內容欄寬完美對齊,隨視窗大小自適應調整。

核心架構:兩個 Table + 同步 scrollLeft

<div id="div1All" style="position:absolute; left:0; right:0; top:0; bottom:0">
  <!-- 固定表頭區 -->
  <div id="divHeaderID" style="overflow:hidden; margin:auto;">
    <table id="headerTable" border="1" cellspacing="0" cellpadding="0" 
           style="border-collapse:collapse; font-size:15px; width:600px">
      <tr style="background:navy; color:white; height:30px">
        <th width="100">Header A</th>
        <th width="100">Header B</th>
        <th width="100">Header C</th>
        <th width="100">Header D</th>
        <th width="100">Header E</th>
        <th width="100">Header F</th>
      </tr>
    </table>
  </div>

  <!-- 內容滾動區 -->
  <div id="divContentID" 
       style="position:absolute; left:0; top:30.5px; bottom:0; right:0; overflow:scroll">
    <table id="contentTable" border="1" cellspacing="0" cellpadding="0"
           style="border-collapse:collapse; font-size:15px; width:600px">
      <tr><td width="100">A</td><td width="100">B</td>...</tr>
      <!-- 多行資料 -->
    </table>
  </div>
</div>

JavaScript 同步邏輯

<script>
// 通用事件綁定(相容 IE 與標準)
function eventHandler(target, handler) {
  if (target.addEventListener) {
    target.addEventListener('scroll', handler, false);
  } else if (target.attachEvent) {
    target.attachEvent('onscroll', handler);
  } else {
    target.onscroll = handler;
  }
}

// 同步水平滾動 + 垂直滾動條顯示控制
function syncScroll(contentId, headerId) {
  var contentDiv = document.getElementById(contentId);
  var headerDiv = document.getElementById(headerId);
  
  var left = contentDiv.scrollLeft;
  headerDiv.scrollLeft = left;  // 核心:同步 scrollLeft

  // 垂直滾動條寬度補償:內容滾到底時,表頭顯示滾動條佔位
  var contentTable = contentDiv.children[0];
  var tableWidth = parseInt(contentTable.style.width.replace('px', ''), 10);
  var divWidth = parseInt(contentDiv.style.width.replace('px', ''), 10);
  var scrollbarWidth = tableWidth - divWidth;
  
  if (contentDiv.scrollLeft >= scrollbarWidth) {
    headerDiv.style.overflowY = 'scroll';  // 顯示佔位滾動條
  } else {
    headerDiv.style.overflowY = 'hidden';
  }
}

// 初始化
window.onload = function() {
  var contentDiv = document.getElementById('divContentID');
  eventHandler(contentDiv, function() {
    syncScroll('divContentID', 'divHeaderID');
  });
};
</script>

關鍵 CSS 要點

  • 兩個 table 寬度相同(範例中均 600px)
  • th/td 寬度對應:每欄明確設定 width
  • border-collapse: collapse:合併邊框,避免 1px 偏移
  • position: absolute + top/bottom/left/right:內容區填滿剩餘空間
  • 表頭 overflow: hidden 預設隱藏垂直滾動條

現代 CSS 方案(無 JS,支援較新瀏覽器)

<style>
.table-wrapper {
  overflow-y: auto;
  height: 400px;  /* 或 max-height */
}

table {
  width: 100%;
  border-collapse: collapse;
}

/* 固定表頭:sticky 定位 */
thead th {
  position: sticky;
  top: 0;
  background: navy;
  color: white;
  z-index: 1;  /* 置於 tbody 之上 */
  border-bottom: 2px solid #ccc;
}

/* 固定第一列(可選) */
tbody th:first-child, td:first-child {
  position: sticky;
  left: 0;
  background: #f5f5f5;
  z-index: 2;
}
</style>

<div class="table-wrapper">
  <table>
    <thead><tr><th>Header</th>...</tr></thead>
    <tbody><tr><td>Data</td>...</tr></tbody>
  </table>
</div>

支援:Chrome 56+、Firefox 59+、Safari 11+、Edge 79+。IE 不支援。

進階:水平滾動同步(現代寫法)

const contentDiv = document.getElementById('content');
const headerDiv = document.getElementById('header');

contentDiv.addEventListener('scroll', () => {
  headerDiv.scrollLeft = contentDiv.scrollLeft;
}, { passive: true });

總結

  • 傳統方案:雙 Table + JS 同步 scrollLeft,全瀏覽器相容(含 IE)
  • 現代方案:單 Table + position: sticky,零 JS、效能更好、程式碼極簡
  • 關鍵細節:欄寬固定、border-collapse、垂直滾動條寬度補償
  • 新專案優先評估 sticky 方案,舊專案維護用雙 Table 方案
copyright © 萬盛學電腦網 all rights reserved