阿里云主机折上折
  • 微信号
Current Site:Index > <tr> - table row

<tr> - table row

Author:Chuan Chen 阅读数:35016人阅读 分类: HTML

Basic Concept of the <tr> Tag

The <tr> tag in HTML is used to define table rows and is a direct child element of the <table> element. Each <tr> represents a row in the table and can contain one or more <td> or <th> cells. This tag is one of the fundamental building blocks for constructing HTML tables.

<table>
  <tr>
    <td>First row, first column</td>
    <td>First row, second column</td>
  </tr>
  <tr>
    <td>Second row, first column</td>
    <td>Second row, second column</td>
  </tr>
</table>

Attributes of the <tr> Tag

Although modern HTML prefers using CSS for styling, the <tr> tag still supports some attributes:

  1. align: Sets the horizontal alignment of content within the row (left/center/right/justify)
  2. valign: Sets the vertical alignment of content within the row (top/middle/bottom/baseline)
  3. bgcolor: Sets the background color of the row (not recommended)
  4. style: Adds inline CSS styles to the row
<table>
  <tr align="center" valign="middle" bgcolor="#f0f0f0">
    <td>Centered</td>
    <td>Gray background</td>
  </tr>
</table>

Relationship Between <tr>, <td>, and <th>

A <tr> must contain at least one <td> (table data cell) or <th> (table header cell). These cells collectively form the content of the table row.

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Occupation</th>
  </tr>
  <tr>
    <td>John Doe</td>
    <td>28</td>
    <td>Frontend Developer</td>
  </tr>
</table>

Row Grouping: <thead>, <tbody>, and <tfoot>

For better semantics and styling control, table rows can be grouped:

<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Sales</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>¥10,000</td>
    </tr>
    <tr>
      <td>February</td>
      <td>¥12,000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>¥22,000</td>
    </tr>
  </tfoot>
</table>

Row-Spanning and Column-Spanning Cells

Using the rowspan and colspan attributes, cells can span multiple rows or columns:

<table border="1">
  <tr>
    <td rowspan="2">Spans two rows</td>
    <td>First row, second column</td>
  </tr>
  <tr>
    <td>Second row, second column</td>
  </tr>
  <tr>
    <td colspan="2">Spans two columns</td>
  </tr>
</table>

<tr> in Responsive Tables

In responsive design, <tr> can be combined with CSS to achieve different display effects:

<style>
  @media (max-width: 600px) {
    table, thead, tbody, th, td, tr {
      display: block;
    }
    tr {
      margin-bottom: 15px;
      border: 1px solid #ddd;
    }
  }
</style>

<table>
  <tr>
    <td data-label="Name">John Doe</td>
    <td data-label="Age">28</td>
  </tr>
</table>

JavaScript Manipulation of <tr>

JavaScript can dynamically manipulate table rows:

// Add a new row
function addRow() {
  const table = document.getElementById("myTable");
  const newRow = table.insertRow();
  const cell1 = newRow.insertCell(0);
  const cell2 = newRow.insertCell(1);
  cell1.innerHTML = "New Data 1";
  cell2.innerHTML = "New Data 2";
}

// Delete a row
function deleteRow(row) {
  const table = document.getElementById("myTable");
  table.deleteRow(row.rowIndex);
}

Accessibility Considerations

Adding appropriate ARIA roles and attributes to <tr> can enhance accessibility:

<table role="grid">
  <tr role="row">
    <td role="gridcell">Data</td>
  </tr>
</table>

Performance Optimization

For large datasets, virtual scrolling can improve table performance:

// Virtual scrolling example
const container = document.getElementById('table-container');
container.addEventListener('scroll', function() {
  const scrollTop = container.scrollTop;
  // Calculate visible rows based on scroll position
  renderVisibleRows(calculateVisibleRows(scrollTop));
});

Table Row Implementation in Frameworks

Implementing dynamic table rows in Vue:

<template>
  <table>
    <tr v-for="(item, index) in items" :key="index">
      <td>{{ item.name }}</td>
      <td>{{ item.value }}</td>
    </tr>
  </table>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { name: 'Item 1', value: 100 },
        { name: 'Item 2', value: 200 }
      ]
    }
  }
}
</script>

Print Style Optimization

Customizing table row styles for print media:

@media print {
  tr {
    page-break-inside: avoid;
  }
  tr:nth-child(odd) {
    background-color: #f2f2f2 !important;
  }
}

Interactive Effects for Table Rows

Adding hover and highlight effects to <tr>:

tr:hover {
  background-color: #f5f5f5;
  cursor: pointer;
}

tr.highlight {
  animation: highlight 2s;
}

@keyframes highlight {
  from { background-color: yellow; }
  to { background-color: transparent; }
}

Complex Table Layouts

Building complex table layouts with <tr>:

<table>
  <tr>
    <td rowspan="2">Logo</td>
    <td colspan="3">Header</td>
  </tr>
  <tr>
    <td>Nav 1</td>
    <td>Nav 2</td>
    <td>Nav 3</td>
  </tr>
</table>

Data Binding for Table Rows

Storing additional information with data attributes:

<table>
  <tr data-id="123" data-category="premium">
    <td>Premium Service</td>
    <td>¥99</td>
  </tr>
</table>

<script>
  document.querySelector('tr').addEventListener('click', function() {
    const id = this.dataset.id;
    const category = this.dataset.category;
    console.log(`ID: ${id}, Category: ${category}`);
  });
</script>

Nested Tables with <tr>

Nesting another table within a table cell:

<table>
  <tr>
    <td>
      Outer Table
      <table>
        <tr>
          <td>Inner Table</td>
        </tr>
      </table>
    </td>
  </tr>
</table>

Sorting Functionality for Table Rows

Implementing client-side table sorting:

function sortTable(columnIndex) {
  const table = document.getElementById("sortable-table");
  const rows = Array.from(table.querySelectorAll("tr:not(:first-child)"));
  
  rows.sort((a, b) => {
    const aText = a.cells[columnIndex].textContent;
    const bText = b.cells[columnIndex].textContent;
    return aText.localeCompare(bText);
  });
  
  rows.forEach(row => table.tBodies[0].appendChild(row));
}

Drag-and-Drop Functionality for Table Rows

Implementing drag-and-drop row reordering:

document.querySelectorAll('tr[draggable="true"]').forEach(row => {
  row.addEventListener('dragstart', e => {
    e.dataTransfer.setData('text/plain', row.rowIndex);
  });
});

document.querySelector('table').addEventListener('dragover', e => {
  e.preventDefault();
});

document.querySelector('table').addEventListener('drop', e => {
  e.preventDefault();
  const fromIndex = e.dataTransfer.getData('text/plain');
  const toRow = e.target.closest('tr');
  if (!toRow) return;
  
  const table = toRow.parentNode;
  const fromRow = table.rows[fromIndex];
  const toIndex = toRow.rowIndex;
  
  if (fromIndex < toIndex) {
    table.insertBefore(fromRow, toRow.nextSibling);
  } else {
    table.insertBefore(fromRow, toRow);
  }
});

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:-表尾部分

下一篇:<th>-表头单元格

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.