鼠标悬停在 HTML table 行时显示透明框(不突出显示行)

Display transparent box on a HTML table row when mouse over (not highlight row)

我想显示一个透明框(上面有一些按钮)围绕用户鼠标悬停的 table 行。我在 Google 上搜索过,但所有页面都只讲述了如何在鼠标悬停时突出显示行。

我使用 JavaScript 添加鼠标悬停事件。

$('tr').on('mouseover', displayBox);

你能帮我解决这个问题或者给我一些参考文章吗?

例如:
Pic

叠加层

我们可以用 :before pseudo elementtbody tr td:first-child:before:

创建叠加层
  • 给定 100% 宽度,将拉伸行的宽度。

  • 它被赋予与 td 相同的高度,并将拉伸行的高度

  • table 是 position: relative 这样单元格 :before 子单元相对于 table 定位并且可以横跨整行.

按钮 div

可以在每行最后一个单元格的 div 中提供按钮 — 不需要 javascript。这需要稍微调整一下,因为它们在 Firefox 中的偏移量稍微太低了。

  • 每行最后一个单元格内的 div 会用 opacity 隐藏,直到悬停该行。悬停时显示为:

    tr:hover td > div {
        opacity: 1;
    }
    
  • td:last-child 被制作成 position: relative 以便具有 position: absolute 的叠加层 div 将相对于其父 td[=23 定位=]

工作示例

* {
  box-sizing: border-box;
}
table,
tr td:last-child {
  position: relative;
}
th,
td {
  padding: 0 10px;
  height: 2em;
}
td > div {
  position: absolute;
  opacity: 0;
  transition: opacity 0.5s;
  right: 0;
  top: 0.5em;
  /* 1/4 height of td*/
  height: 2em;
  /*height of td*/
}
tr:hover td > div {
  opacity: 1;
}
tbody tr td:first-child:before {
  width: 100%;
  content: '';
  display: block;
  height: 2em;
  position: absolute;
  background: rgba(0, 0, 0, 0);
  margin-top: -6px;
  /* off set space above text */
  left: 0;
  transition: background 0.5s;
}
tbody tr:hover td:first-child:before {
  background: rgba(0, 0, 0, 0.6);
}
td > div > a {
  margin: 0 0.25em 0 0;
  background: #1DE9B6;
  color: #FFF;
  text-decoration: none;
  border-radius: 2px;
  padding: 3px;
  transition: color 0.5s, background 0.5s;
}
/*Not important -- example only*/

td > div > a:hover {
  background: #A7FFEB;
  color: #000;
}
table {
  border-collapse: collapse;
  border: solid 1px #EEE;
}
th,
td {
  border: solid 1px #EEE;
  transition: background 0.5s;
}
tr:nth-child(even) {
  background: #E3F2FD;
}
<table>
  <thead>
    <tr>
      <th>Heading</th>
      <th>Heading</th>
      <th>Heading</th>
      <th>Heading</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Content</td>
      <td>Content</td>
      <td>Content</td>
      <td>Content
        <div><a href="#">Action</a><a href="#">Action</a><a href="#">Action</a></div>
      </td>
    </tr>
    <tr>
      <td>Content</td>
      <td>Content</td>
      <td>Content</td>
      <td>Content
        <div><a href="#">Action</a><a href="#">Action</a><a href="#">Action</a></div>
      </td>
    </tr>
    <tr>
      <td>Content</td>
      <td>Content</td>
      <td>Content</td>
      <td>Content
        <div><a href="#">Action</a><a href="#">Action</a><a href="#">Action</a></div>
      </td>
    </tr>
    <tr>
      <td>Content</td>
      <td>Content</td>
      <td>Content</td>
      <td>Content
        <div><a href="#">Action</a><a href="#">Action</a><a href="#">Action</a></div>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="4">Footer</td>
    </tr>
  </tfoot>
</table>