javascript - 在鼠标悬停时显示复选框显示表格中的每个单元格

标签 javascript html css asp.net-mvc checkbox

我有一个表格(如下所示),其中每个单元格都有一个复选框,在用户将鼠标悬停在该单元格上之前,该复选框一直处于隐藏状态。如果复选框被选中,当鼠标离开单元格时它将保持显示状态,否则复选框将再次隐藏。

enter image description here

我遇到的问题是我不知道如何为用户当前悬停的单个单元格显示复选框。此时,将鼠标悬停在任何单元格上将显示如下所示的每个复选框:

enter image description here

我对单元格设置位置的看法:

@for (int i = 0; i < Model.Users.Count(); i++) {
    <tr>
         @for (int j = 0; j < Model.Users.Count(); j++) {
             string background = Model.AssignedArray[i] == j ? "background-color:#157fa0" : null;
             string text = Model.AssignedArray[i] == j ? "color:#ffffff" : null;
             <td class="tableCell" style="text-align: center; @background; @text">
                 @Model.Matrix[i, j]
                 <input type="checkbox" class="hideCheckBox" name="forcedAssigned" value="">
             </td>
          }
      </tr>

用于复选框的 JavaScript:

<script>
    $('.tableCell')
        .mouseenter(function () {

            $(".hideCheckBox").show();
        })
        .mouseleave(function () {
            if ($(".hideCheckBox").is(":checked"))
                $(".hideCheckBox").show();
            else
                $(".hideCheckBox").hide();
        });
</script>

CSS:

.hideCheckBox {
    display: none;
}

我的脚本是错误的,但我不知道如何修复以处理单个单元格。

最佳答案

您无需使用 javascript 即可轻松实现这一目标。只需将input type="checkbox"的默认display设置为none,当td:hovered,或者 input type="checkbox":checked,覆盖 display 属性,像这样:

td {
  border: solid 1px red;
  margin: 5px;
  width: 40px;
  height: 40px;
}

td input { display: none; }

td:hover input { display: inline; }

td input:checked {display: inline; }
<table>
  <tr>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
  </tr>
  <tr>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
  </tr>
  <tr>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
  </tr>
  <tr>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
    <td><input type ="checkbox" /></td>
  </tr>
</table>

关于javascript - 在鼠标悬停时显示复选框显示表格中的每个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42204265/

相关文章:

javascript - Dojo 需要单参数同步吗?

javascript - 从 Repeater QML/JS 创建一个动态数量的 AppCheckBoxes

javascript - 仅在 iOS 中返回透明图像的 webgl Canvas 的 toDataURL()

html - 如何为html <p>设置行间距

PHP 用链接链接同一页面并通过 $_POST 发送数据

javascript - 将 Javascript 对象传递给 HTML iframe(作为对象)

html - 奇怪的 CSS 格式错误

html - Bootstrap - 屏幕上的错误列

javascript - HTML - 使表格最小高度与当前屏幕高度匹配

html - 如何在 SASS 中使用 Bootstrap 4 媒体断点?