javascript - 如何加深html表格中重叠单元格的颜色
问题描述
我有 html 表格,我想加深重叠单元格的颜色。
例如,当我单击 cell 时2
,.nextAll(':lt(5)')
方法更改类下一个4
单元格。
然后当我单击3
单元格时,颜色会改变。我想要的结果如下所示。重叠单元格的颜色将按照以下公式更改。
background-color: hsl(60,100%,95%);
→<code>背景色:hsl(60,100%,90%);
有什么方法可以实现吗?
谢谢。
$(function() {
$("td").click(function() {
$(this).nextAll(':lt(4)').addClass('color');
});
});
table td {
width: 20px;
overflow: hidden;
display: inline-block;
white-space: nowrap;
border: 1px solid gray;
text-align: center;
padding: 5px;
cursor: pointer;
}
.color {
background-color: hsl(60,100%,95%);
}
.color2 {
background-color: hsl(60,100%,90%);
}
.color3 {
background-color: hsl(60,100%,85%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
解决方案
您可以将.each()
函数链接到.nextAll()
结果,然后用于.hasClass()
单独确定每个单元格应使用哪种颜色。
$(function() {
$("td").click(function() {
$(this).nextAll(':lt(4)').each(function(i) {
if ($(this).hasClass("color2")) {
$(this).addClass('color3');
}
else if ($(this).hasClass("color")) {
$(this).addClass('color2');
}
else {
$(this).addClass('color');
}
console.log(i);
});
});
});
table td {
width: 20px;
overflow: hidden;
display: inline-block;
white-space: nowrap;
border: 1px solid gray;
text-align: center;
padding: 5px;
cursor: pointer;
}
.color {
background-color: hsl(60,100%,95%);
}
.color2 {
background-color: hsl(60,100%,90%);
}
.color3 {
background-color: hsl(60,100%,85%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
它可能需要一些调整来删除不需要的类,但我测试过并且似乎可以正常工作。
推荐阅读
- java - 以毫秒为单位了解位和时间
- go - 在 Go 中以 1:1 的比例打印圆形轮廓
- angular - Angular 管道未触发响应式表单数据更改
- postgresql - 将 Postgres LAG 与 TEMP 表一起使用
- html - css卡翻转如何解决这个问题?
- keyboard - 在 iterm 中禁用 Control-Right/left
- r - 使用 R Shiny 演示神经网络
- aws-lambda - AWS Step Functions:如何使用 Pass 步骤“重命名”输入参数
- docusignapi - “开始”按钮缺失/无表单自动导航
- html - 反应组件中的粗体文本?