悬停图片以删除行

时间:2016-03-07 17:47:09

标签: html css

目标:将鼠标悬停在表格行<tr>上会导致按钮在<tr>元素右侧(表格外部)可见。单击此按钮将删除该行。

我在使用CSS和显示按钮的机制上挣扎。我发现我能够在<div>标记上创建所需的按钮隐藏/显示行为,但我无法弄清楚如何在表格中实现它。

See fiddle here

实际删除行对我来说相当简单......

$('table tr input').click(function(e) {
  var answer = confirm("Delete row?")
  if (answer) {

   var ind=$(this).closest('td').parent()[0].sectionRowIndex;
   $("tr:eq("+ind+")").remove();

  } else {
    //some code
  }

});

2 个答案:

答案 0 :(得分:2)

关于“表外”的要求,您可以尝试将按钮放在第4列中,而不是将绝对/相对位置与行位置匹配。而不是将边框应用于表格,将其应用于TD,并关闭边框或第4列。这将使您的按钮与行对齐,但看起来好像它在表格之外。

https://jsfiddle.net/sg2y9fya/

.show-image td {
  border: solid 1px black;
}

.show-image th {
  border-top: solid 1px black;
}

.show-image th:first-child {
  border-left: solid 1px black;
}

.show-image th:last-child {
  border-right: 1px solid black;
}

.show-image td:last-child {
  border: 0;
}

.show-image td:last-child input {
  display:none;
}

.show-image tr:hover > td:last-child > input {
  display:block;
}

table.show-image {
  table-padding: 0;
  table-spacing: 0;
  border-collapse: collapse;
}
<table class="show-image">
  <tr>
    <th>header1</th>
    <th>header2</th>
    <th>header3</th>
  </tr>
  <tr>
    <td>data1</td>
    <td>data2</td>
    <td>data3</td>
    <td><input class="row-del-btn" type="button" value=" Delete " /></td>
  </tr>
  <tr>
    <td>data4</td>
    <td>data5</td>
    <td>data6</td>
    <td><input class="row-del-btn" type="button" value=" Delete " /></td> 
  </tr>
    <tr>
    <td>data7</td>
    <td>data8</td>
    <td>data9</td>
    <td><input class="row-del-btn" type="button" value=" Delete " /></td>
  </tr>
</table>

答案 1 :(得分:1)

这很容易,只有两个CSS规则:

&#13;
&#13;
$('table td:last-child button').click(function(e) {
  var answer = confirm("Delete row?")
  if (answer) {

   var $row = $(this).closest('tr');
   $row.remove();

  } else {
    //some code
  }

});
&#13;
tr > td:last-child > button {visibility:hidden;}
tr:hover > td:last-child > button {visibility:visible;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="show-image">
  <tr>
    <th>header1</th>
    <th>header2</th>
    <th>header3</th>
  </tr>
  <tr>
    <td>data1</td>
    <td>data2</td>
    <td>data3<button>x</button></td>
    
  </tr>
  <tr>
    <td>data4</td>
    <td>data5</td>
    <td>data6<button>x</button></td>
  </tr>
    <tr>
    <td>data7</td>
    <td>data8</td>
    <td>data9<button>x</button></td>
    
  </tr>
</table>
&#13;
&#13;
&#13;