一次突出显示多个表格单元格

时间:2018-03-05 06:09:02

标签: javascript html css

我的网页上有两张桌子并排。当鼠标悬停在第一桌或第二桌上的单元格上时(例如单元格(2,5)),我想要突出显示第一个表格的单元格(2,5)和第二个表格的第二个表格。 s单元格(2,5)同时。我已经用Css尝试了它,但我认为用Css做它是不可能的。

1 个答案:

答案 0 :(得分:2)

使用一些jQuery代码来获取魔力,请查看我的代码段

$('table td').hover(function(){
  // Highlight
  var curentEl = $(this);
  var outerEl = curentEl.closest('.outer');
  var col = $(this).parent().children().index($(this));
  var row = $(this).parent().parent().children().index($(this).parent());
  outerEl.find('table').each(function() {
    $(this).find('tr:eq('+ row +')' + ' ' + 'td:eq('+ col +')').addClass('hover');
  });
}, function() {
  //Removing Highlight when mouse out
  $(this).closest('.outer').find('.hover').removeClass('hover');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 40%;
    float: left;
}

table:nth-child(2) {
 margin-left: 5%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

td.hover {
 border-color: red;
 background: #ddd;
}

</style>
</head>
<body>

<h2>HTML Table</h2>
<div class="outer">
  <table>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
  <table>
    <tr>
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
</div>
</body>
</html>