如何使某些表格单元格/表格中的单元格在点击时消失?

问题描述 投票:0回答:1

我正在尝试为表格创建一个 javascript 函数。

我试图做到这一点,以便当单击某个元素(或本例中的表格单元格)时,同一表格行中的其他元素消失,并且单击的元素移动到最左侧。右侧将打开一个滑块,显示有关元素等的信息。但是,我想不出一种方法来使用元素执行 onclick 函数来执行元素消失并且单击的元素移动到最左侧的函数。我对 javascript 了解不多,我不知道是否有一个函数可以直接使表格单元格显示:无,或者像一个函数,使表格单元格 colspan 超过其他单元格。

我的 html 表:

<table id='TrendGames'>
    <tr>
        <td>
        <img class='GameCover' src='.png'>
        </td>
        <td>
        <img class='GameCover' src='.png'>
        </td>
        <td>
        <img class='GameCover' src='.png'>
        </td>
        <td>
        <img class='GameCover' src='.png'>
        </td>
    </tr>
</table>
javascript display tablecell
1个回答
0
投票

这是一个脚本,其中单击的单元格将展开以占据该行单元格的空间。

document.addEventListener('DOMContentLoaded', function() {
  var table = document.getElementById('TrendGames');
  table.addEventListener('click', function(event) {
    var clickedCell = event.target.closest('td');
    if (clickedCell) {
      handleCellClick(clickedCell);
    }
  });
});

function handleCellClick(clickedCell) {
  var row = clickedCell.parentElement;
  var cells = row.children;

  // Hide other cells and rearrange the clicked cell
  for (var i = 0; i < cells.length; i++) {
    if (cells[i] !== clickedCell) {
      cells[i].style.display = 'none';
    }
  }
  row.insertBefore(clickedCell, row.firstChild); // Move to the leftmost
  clickedCell.colSpan = cells.length
  // Open the slider and display information
  openSlider(clickedCell);
}

function openSlider(cell) {
  // Implement the slider logic here
  console.log(cell.id)
}
#TrendGames td {
    border: 1px solid black; 
    padding: 5px; 
}
<table id='TrendGames'>
  <tbody>
    <tr>
      <td id="cell1"> Cell 1
        <img class='GameCover' src='.png' alt="cell1" />
      </td>
      <td id="cell2">Cell 2
        <img class='GameCover' src='.png' alt="cell2" />
      </td>
      <td id="cell31">Cell 3
        <img class='GameCover' src='.png' alt="cell3" />
      </td>
      <td id="cell4">Cell 4
        <img class='GameCover' src='.png' alt="cell4" />
      </td>
    </tr>
    <tr>
      <td id="cell1"> Cell 1
        <img class='GameCover' src='.png' alt="cell1" />
      </td>
      <td id="cell2">Cell 2
        <img class='GameCover' src='.png' alt="cell2" />
      </td>
      <td id="cell31">Cell 3
        <img class='GameCover' src='.png' alt="cell3" />
      </td>
      <td id="cell4">Cell 4
        <img class='GameCover' src='.png' alt="cell4" />
      </td>
    </tr>
  </tbody>
</table>

© www.soinside.com 2019 - 2024. All rights reserved.