[英]How can I get the width of the table header and have the same size as the table cell in JQuery?
我有兩張單獨的表格:一張用於標題,一張用於內容。 這是我的表,只有標題:
<table class="table table-sm table-bordered >
<thead>
<tr>
<th class="header-length">This is header one</th>
<th class="header-length">short</th>
<th class="header-length">X</th>
</tr>
</thead>
</table>
這是我的第二張包含內容的表格
<table class="table table-sm table-bordered>
<tbody>
<tr>
<td>This content must align with header one</td>
<td>very short</td>
<td>Icon</td>
</tr>
</tbody>
</table>
我希望標題的width
通過JQuery對齊內容我已經使用這個選擇器來獲取屬性
$('.header-length').width;
表格單元格的標題必須與<td>
的內容具有相同的寬度
如何使用 JQuery 使th
屬性的寬度與td
寬度相同?
width
是一個函數。
您可以應用循環來獲取每個th
寬度。
$('.header-length').each(function() { console.log($(this).width()); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="table table-sm table-bordered"> <thead> <tr> <th class="header-length">This is header one</th> <th class="header-length">short</th> <th class="header-length">X</th> </tr> </thead> </table>
- 編輯 -
const thWidthArr = [...document.querySelectorAll('.header-length')].map(th => th.offsetWidth); const table2 = document.querySelectorAll('table')[1]; table2.querySelectorAll('td').forEach((td, i) => { td.style.width = thWidthArr[i] + 'px'; })
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <table class="table table-sm table-bordered"> <thead> <tr> <th class="header-length">This is header one</th> <th class="header-length">short</th> <th class="header-length">X</th> </tr> </thead> </table> <table class="table table-sm table-bordered"> <tbody> <tr> <td>This content must align with header one</td> <td>very short</td> <td>Icon</td> </tr> </tbody> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.