在JavaScript中设置<td>
元素的高度自适应,通常需要考虑以下几个方面:
以下是一个简单的示例,展示如何使用JavaScript设置<td>
元素的高度自适应:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TD Height Auto Adjust</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
td {
border: 1px solid #000;
padding: 10px;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Short content</td>
<td>This is a longer piece of content that should make the cell taller.</td>
</tr>
<tr>
<td>Another short content</td>
<td>Even more content to demonstrate the auto-adjust feature.</td>
</tr>
</table>
<script>
function adjustTDHeight() {
const table = document.getElementById('myTable');
const rows = table.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
const cells = rows[i].getElementsByTagName('td');
let maxHeight = 0;
for (let j = 0; j < cells.length; j++) {
const cellHeight = cells[j].scrollHeight;
if (cellHeight > maxHeight) {
maxHeight = cellHeight;
}
}
for (let j = 0; j < cells.length; j++) {
cells[j].style.height = `${maxHeight}px`;
}
}
}
// Adjust height on window resize
window.addEventListener('resize', adjustTDHeight);
// Initial adjustment
adjustTDHeight();
</script>
</body>
</html>
adjustTDHeight
函数遍历表格的每一行和每一个单元格。scrollHeight
(内容的实际高度)。通过这种方式,可以确保<td>
元素的高度能够根据内容自动调整,从而提供更好的用户体验。
领取专属 10元无门槛券
手把手带您无忧上云