使用 z 索引选中复选框时创建颜色叠加

Create color overlay when checkbox selected using z-index

本文关键字:创建 颜色 叠加 复选框 索引 使用      更新时间:2023-09-26

>我有一个复选框,用于选择包含产品信息的表。选择后,css 样式将覆盖 30% 的颜色,以便很明显该项目被选中。

仅使用 css 和 jquery,我可以调用具有比用于直观查看叠加的图像更大的 z 索引的样式。叠加样式有效并显示正确的 z 索引,但不在图像上。

使用 Jquery,我强制将图像的 z 索引恢复为 -10 值。仍然显示在彩色div的顶部...我甚至可以强制同一 Jquery 中的div 移动到 z-index 105,但它仍然没有显示在较小 z 索引上的图像顶部。

我认为问题是接收更大 z 索引的div 将 UP 中的所有内容作为起点,因此嵌套图像也在 z 索引级别上移。

如果是这种情况,如何最好地在一系列需要用 30% 不透明度样式覆盖的动态生成的表上进行叠加?

更新的工作代码:

 $(function ()
    {          
        $("input[type='checkbox']").change(function ()
        {
            if ($(this).is(":checked"))
            {
                $(this).parent().addClass("jobSelected");
            } else
            {
                $(this).parent().removeClass("jobSelected");
            }
        });
    });   
    </script>

<style type="text/css">
.jobSelected {
    background-color: hsla(0,0%,0%,0.50);
    position: relative;
}
</style>

更新的工作代码:

<div>
  <table  cellpadding="6" cellspacing="0" border="0" width="100%">
    <thead>
      <tr>
        <td> Item 1 </td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><img src="http://sgdesign.com/temp/temp1.png" alt="" style="z-index:-1; position:relative;"></td>
      </tr>
    </tbody>
  </table>
  <input type="checkbox" name="checkbox" id="checkbox">
  Select </div>

<br>
<br>

<div>
  <table  cellpadding="6" cellspacing="0" border="0" width="100%">
    <thead>
      <tr>
        <td > Item 2 </td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td valign="top" style="border-left:0px none;padding-left:12px;"><img src="http://sgdesign.com/temp/temp2.png" alt="" style="z-index:-1; position:relative;"></td>
      </tr>
    </tbody>
  </table>
    <input type="checkbox" name="checkbox2" id="checkbox2">
  Select </div>

上面的代码在设置预期值方面做得很好,这些值可以通过执行浏览器检查元素来查看,但结果没有实现目标。

您是对的,Z 索引更改不会级联,因为您正在处理一个表。为了解决这个问题,请直接在需要的div 上更改 z 索引。

尝试将 CSS 更改为以下内容:

.jobSelected {
    background-color: hsla(0,0%,0%,0.30);
    position: relative;
}
.jobSelected div.overlay {
    z-index: 50;
}

当然,你的HTML也应该更新:

    <tr>
    <td valign="top" style="border-left:0px none;padding-left:12px;">
        <div style="z-index:100; position:relative;" class="overlay">
            <img src="http://sgdesign.com/temp/temp1.png" alt="" style="z-index:-1; position:relative;">
        </div>
    </td>
    </tr>

解决方案是确保没有元素将所选内容包装在比动态更新值更高的 z 值中。

例如:

  <tr>
    <td valign="top" style="border-left:0px none;padding-left:12px;">
        <div style="z-index:100; position:relative;" class="overlay">
            <img src="http://sgdesign.com/temp/temp1.png" alt="" style="z-index:-1; position:relative;">
        </div>
    </td>
    </tr>

我们看到一个div 以 100 的 z 索引深度包裹图像,而 jquery 设置的 css 为 50。删除具有 100 z 索引值的div 允许 jquery 更新的 css 在 50 正确覆盖。